【发布时间】:2014-11-22 02:47:19
【问题描述】:
我正在尝试在控制台应用程序中使用此代码创建一个 Partial 数组。我要做的是在一个 Console.ReadLine 上输入多个值(示例测试分数),取输入数字的总和,但如果用户输入小于 LIMIT,例如输入 5 个值,但有空间总共 10 个,它只会将这 5 个值相加。
我希望能够在一行上使用数组输入多个值,但如果我不在int [] scores = {0, 1, 2, ...]; 中为每个参数输入值,它应该能够将用户输入的数字相加,而忘记休息。例如,如果我在一行输入 56 76 86,然后输入 0 终止数组,它将相加 56 76 86,并且不需要其他数字来填充数组。
class Program
{
const int LIMIT = 10;
static void Main(string[] args)
{
//Declarations:
//Array Size
//Array Scope
int[] examScores = new int[LIMIT];
//Define an Array of integers:
int testNum = 1;
int [] scores = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//1. Ask User Method:
//a.)Ask user to input numbers.
//b.)Save user numbers in an array
Console.WriteLine("Input all of your test scores as the program prompts of");
Console.WriteLine("each score on the lines below. (i.e. 89 25 87 98...)");
//Purpose of this for method is to get user input and save to
//an array.
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine("\nEnter test score #{0}", testNum);
scores[i] = int.Parse(Console.ReadLine());
}
PrintScores(scores);
Console.Read();
}//End Main.
//2. AddSum Method.
//Purpose: Take users input and add all numbers together.
//Paramiters: Array numbers from Main saved as PrintScores
//Returns: None
//Prints: Sum of Scores.
static void PrintScores(int[] scr)
{
int result = 0;
for (int i = 0; i < scr.Length; i++)
{
result += scr[i];
}
Console.WriteLine("\n--------------------------------------");
Console.WriteLine("Sum of your test scores equal: {0}", result);
}
}
}
【问题讨论】:
-
您的实际问题是什么? 具体你有什么困难?见stackoverflow.com/help/how-to-ask
-
我希望能够使用数组输入多个值,但如果我没有在 {int [] score = {0, 1, 2, ...];} 中为每个参数输入值它应该能够将用户输入的数字相加,而忘记其余的。例如,如果我在一行输入 56 76 86,然后输入 0 终止数组,它将相加 56 76 86,并且不需要其他数字来填充数组。
-
@GoodyGoodmansen 那么你应该使用
List<int>而不是数组。数组必须有固定的大小;列表没有。 -
@D Stanley 我想拆分它,以便将所有值输入一行,然后加在一起,但可以部分输入。