我想在控制檯應用程序中使用此代碼創建一個部分數組。我想要做的是在一個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