我正在尝试使用使用数组的程序在测试中输出整体班级平均值。该计划是针对一个 12 名学生的班级。当我尝试输入我需要的所有数据时,我没有得到整个班级的平均值。问题显然在于普通计算器本身,但鉴于我是初学者,我几乎不知道如何解决它。任何帮助,将不胜感激。重申一下,我正在寻找一个解决方案,以解决如何修复我的平均计算器以给出班级平均水平。我在下面输入了我的代码。我希望我已经具体了。
string[] studentnames = new string[12];
int[] testscore = new int[12];
int i;
int index;
double average;
int total = 0;
//title
Console.Write("\n\nStudent lists:\n");
Console.Write("******************\n");
//asks user to input names
Console.Write("Enter student names:\n");
for (i = 1; i < 12; i++)
{
Console.Write("Student name {0} : ", i);
studentnames[i] = (Console.ReadLine());
//asks user to enter student's test score
Console.Write("Please enter their test score: ");
testscore[i] = Convert.ToInt32(Console.ReadLine());
}
//outputs all values user has entered
Console.WriteLine("\nStudent marks: ");
for (i = 1; i < 12; i++)
{
Console.WriteLine("Name: ");
Console.WriteLine("{0} ", studentnames[i]);
Console.WriteLine("Test score: ");
Console.WriteLine("{0} ", testscore[i]);
}
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
average = total / 12;
Console.WriteLine("The class average was: " + average);
}
Console.ReadKey();
除以总数需要在for
循环之后。
这个:
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
average = total / 12;
Console.WriteLine("The class average was: " + average);
}
需要变成:
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
}
average = ((double)total) / 12;
Console.WriteLine("The class average was: " + average);
另一个问题:你的for
循环从索引 1 开始。C# 使用基于 0 的索引。我假设你正在尝试计算 12 名学生的平均值,而不是 11 名。
另外,看在上帝的份上,请停止写数字12
。如果你绝对必须对其进行硬编码,请使用常量。
编辑:我已经更新了我的回答来解释flydog的评论
@yeok:另外,如果你希望你的平均值是 a
double
,不要将两个整数相除——它会得到一个整数(例如,如果你的总数是 825,当你将 825 除以 12 时,你会得到68,而不是 68.75)。将平均计算更改为average = (double) total / 12
; 由于股息是双倍的,因此结果将是双倍的。或者,您可以先声明total
为双精度:double total = 0.0;