C#——数组问题.未读取用户输入
本文关键字:用户 输入 读取 问题 数组 | 更新日期: 2023-09-27 18:25:13
所以我试图制作一个控制台程序,从用户那里获取10个数字,然后将它们相加,然后求和的平均值。在do while循环中,程序应该不断询问下一个数字。
{
Console.WriteLine("Hey there! If you could go ahead and just give me like 10 numbers, that'd be great... And I'll tell you what, if you do, I'll add them up and average them all up for ya.");
// declare an array of strings
int[] aryNumbers;
int intSum = 0;
int intAverage = 0;
// initialize the array
aryNumbers = new int[10];
aryNumbers[0] = int.Parse(Console.ReadLine());
aryNumbers[1] = int.Parse(Console.ReadLine());
aryNumbers[2] = int.Parse(Console.ReadLine());
aryNumbers[3] = int.Parse(Console.ReadLine());
aryNumbers[4] = int.Parse(Console.ReadLine());
aryNumbers[5] = int.Parse(Console.ReadLine());
aryNumbers[6] = int.Parse(Console.ReadLine());
aryNumbers[7] = int.Parse(Console.ReadLine());
aryNumbers[8] = int.Parse(Console.ReadLine());
aryNumbers[9] = int.Parse(Console.ReadLine());
do
{
Console.WriteLine("Okay, give me a number.");
aryNumbers[] = int.Parse(Console.ReadLine());
} while (intSum != 0);
int intNumbers = aryNumbers.Length;
//for loop to average sum of array elements
for (int i = 0; i < intNumbers; i++)
{
intSum += aryNumbers[i];
}
intAverage = intSum / intNumbers;
Console.WriteLine("You're average comes out to... " + intAverage);
Console.ReadKey();
}
}
我真的不知道该怎么办,我对这个很陌生
感谢
您的代码有很多问题。我认为你应该读一整章关于数组的内容。下面是MSDN上的教程。
这是我的代码:
using System.Linq;
.....
Console.WriteLine("Hey there! If you could go ahead and just give me like 10 numbers, that'd be great... And I'll tell you what, if you do, I'll add them up and average them all up for ya.");
// declare the array
int[] aryNumbers = new int[10];
for(int i =0; i<aryNumbers.Length;i++)
{
Console.WriteLine("Okay, give me a number.");
aryNumbers[i] = int.Parse(Console.ReadLine());
}
int intAverage = (int)aryNumbers.Average();
Console.WriteLine("You're average comes out to... " + intAverage);
Console.ReadKey();