我想在控制台应用程序中使用此代码创建一个部分数组。我想要做的是在一个Console.ReadLine上输入多个值(例如测试分数),取得输入数字的总和,但是如果用户输入小于LIMIT,例如输入5个值,但是有空间总共10个,它会将这5个值加起来。如何在C中创建一个部分填充的数组#
我希望能够在一行上使用数组输入多个值,但如果我不输入每个参数的值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);
}
}
}
你的实际问题是什么?你有什么特别的困难?请参阅http://stackoverflow.com/help/how-to-ask – 2014-11-22 03:13:18
我希望能够使用数组输入多个值,但是如果我不输入每个参数的值{int [] scores = {0,1 ,2,...];}它应该能够将用户输入的数字相加,并忘记其余的。例如,如果我在一行中输入56 76 86,则输入0终止阵列,它将加起来56 76 86,而不需要其他数字来填充阵列。 – 2014-11-22 03:28:32
@GoodyGoodmansen然后你应该使用'List'而不是数组。数组必须具有固定的大小;列表不。 –
2014-11-22 03:42:38