将整数从Console存储到数组

时间:2013-08-15 16:32:07

标签: c# arrays

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

所以,我试着这样做:

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

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

1 个答案:

答案 0 :(得分: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);