当我运行此代码时:
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'数字的平均值。
答案 0 :(得分:1)
在for中,你必须替换变量&#39; n&#39;通过&#39; i&#39;。
像这样:
(...)
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];
}
(...)