Console.Write ("How many students do you have?: ");
student = Convert.ToInt32 (Console.ReadLine ());
int[] numberOfStudents = new int[student];
for (int i = 1; i <= numberOfStudents.Length; i++) {
Console.Write ($"Enter student {i}'s current grade: ");
numberOfStudents [i] = Convert.ToInt16 (Console.ReadLine ());
}
int sum = 0;
for(int i = 0; i < numberOfStudents.Length; i++)
{
sum += numberOfStudents[i];
}
average = sum / numberOfStudents.Length;
Console.WriteLine ($"Your student average is {average}.");
Console.ReadLine ();
基本上,用户输入学生数量并确定数组的长度。 for循环收集稍后计算平均值的所有标记。
出于某种原因,如果for循环达到第五个时numberOfStudents
长度是5,那就要求学生标记但是当你输入它而不是得到总和并计算平均值时程序会崩溃system.indexoutofrange
错误。
感谢您的帮助!
答案 0 :(得分:6)
在C#数组中,起始索引是0而不是1,所以你只需要在你的第一个for循环中用0初始化i,你的代码将完全正常工作。 请尝试以下代码:
Console.Write ("How many students do you have?: ");
student = Convert.ToInt32 (Console.ReadLine ());
int[] numberOfStudents = new int[student];
for (int i = 0; i <= numberOfStudents.Length; i++) {
Console.Write ($"Enter student {i+1}'s current grade: ");
numberOfStudents [i] = Convert.ToInt16 (Console.ReadLine ());
}
int sum = 0;
for(int i = 0; i < numberOfStudents.Length; i++)
{
sum += numberOfStudents[i];
}
average = sum / numberOfStudents.Length;
Console.WriteLine ($"Your student average is {average}.");
Console.ReadLine ();
答案 1 :(得分:1)
数组从索引0开始,因此当尝试选择最后一个值时,第一个for循环将超出边界(因为i
变量将来自索引1 => 6
)。
for (int i = 1; i <= numberOfStudents.Length; i++) {
// The i variable is starting on 1, loops til the index is greater than 5 (I.E., 6)
Console.Write ($"Enter student {i}'s current grade: ");
numberOfStudents [i] = Convert.ToInt16 (Console.ReadLine ());
// On last fetch the variable i is 6, trying to fetch from array where last index is 5
// will make the array throw an exception.
}
要解决此问题,您可以在索引0上启动循环,然后像在第二个循环(for (i=0;i<numberOfStudents.Length;i++)
)中那样循环它,然后在输出中添加+1以使输出从1开始的。
或者只是更改从数组中获取的部分以获取i - 1
。