-4

我正在编写一个程序,从控制台向控制台询问 x 数字。如果他们选择数字 4,则应存储 4 个不同的数字。然后程序必须将所有这些输入的数字存储在一个数组中,然后将这些数字相加并在控制台中打印出来。

所以,我试着做:

Console.WriteLine("Write out a number: ");
        int[] x = int[].Parse(Console.ReadLine());

显然你不能以这种方式从控制台读取数组元素,所以我需要将它们存储在变量中,然后将它们添加到新数组中吗?

4

1 回答 1

2
Console.Writeline("Enter the number of numbers to add: ");
//Yes, I know you should actually do validation here
var numOfNumbersToAdd = int.Parse(Console.Readline());

int value;
int[] arrayValues = new int[numOfNumbersToAdd];
for(int i = 0; i < numOfNumbersToAdd; i++)
{
    Console.Writeline("Please enter a value: ");
    //Primed read
    var isValidValue = int.TryParse(Console.Readline(), out value);
    while(!isValidValue) //Loop until you get a value
    {
        Console.WriteLine("Invalid value, please try again: "); //Tell the user why they are entering a value again...
        isValidValue = int.TryParse(Console.Readline(), out value);
    }
    arrayValues[i] = value; //store the value in the array
}
//I would much rather do this with LINQ and Lists, but the question asked for arrays.
var sum = 0;
foreach(var v in arrayValues)
{
    sum += v;
}
Console.Writeline("Sum {0}", sum);
于 2013-08-15T16:46:08.437 回答