错误:索引超出了数组的边界
本文关键字:数组 边界 索引 错误 | 更新日期: 2023-09-27 18:08:37
当我运行这段代码时:
Console.Write("How many numbers do you wish to enter? ");
int n = int.Parse(Console.ReadLine());
int[] arrayOfNumbers = new int[n];
for (int i = 0; i < n; i++)
{
Console.Write("Enter number [{0}]: ", i + 1);
arrayOfNumbers[i] = int.Parse(Console.ReadLine());
}
int minNumber = arrayOfNumbers[0];
int maxNumber = arrayOfNumbers[0];
int sumOfNumbers = 0;
for (int i = 0; i < n; i++)
{
if (arrayOfNumbers[n] < minNumber)
{
minNumber = arrayOfNumbers[n];
}
else if (arrayOfNumbers[n] > maxNumber)
{
maxNumber = arrayOfNumbers[n];
}
sumOfNumbers += arrayOfNumbers[n];
}
double sumDouble = (double)sumOfNumbers;
double average = sumDouble / n;
Console.Write("The min number is : {0}", minNumber);
Console.Write("The max number is : {0}", maxNumber);
Console.Write("The sum of the numbers is : {0}", sumOfNumbers);
Console.Write("The average sum of the numbers is : {0:f2}", average);
它给了我一个错误:索引超出了数组的边界。
错误在第28行。
我有一个任务,找到最小和最大的数字+和和平均的'n'个数字。
在for语句中,必须将变量'n'替换为'i'。
:
(...)
for (int i = 0; i < n; i++)
{
if (arrayOfNumbers[i] < minNumber)
{
minNumber = arrayOfNumbers[i];
}
else if (arrayOfNumbers[i] > maxNumber)
{
maxNumber = arrayOfNumbers[i];
}
sumOfNumbers += arrayOfNumbers[i];
}
(...)