我正在嘗試創建一個程式,該程式輸入一連串數字,直到輸入“-1”。然后,程式將輸出輸入的數字中的最高和最低。這是我所擁有的:
int[] numbers = new int[]; // Creating a blank array.
int number, max, min;
Console.Write("Enter a number: ");
number = Convert.ToInt32(Console.ReadLine());
while (number != -1)
{
// This line would append user input to the array.
Console.Write("Enter another number (Enter -1 to stop): ");
number = Convert.ToInt32(Console.ReadLine());
}
max = numbers[0];
min = numbers[0];
for (int i = 1; i < numbers.Length; i )
{
if (numbers[i] > max)
{
max = numbers[i];
}
if (numbers[i] < min)
{
min = numbers[i];
}
}
Console.Write("The largest number you entered was: {0}, and the smallest number you entered was: {1}.", max, min);
uj5u.com熱心網友回復:
既然你不知道號碼的用戶的數量將進入你不應該使用arrays,而不是我建議使用List如串列支持遠遠更像操作add或remove
uj5u.com熱心網友回復:
我認為這會幫助你:
private const int EndOfInput = -1;
private static void Main(string[] args)
{
int currentInput;
var allInput = new List<int>();
do
{
Console.Write("Enter another number (Enter -1 to stop): ");
if (int.TryParse(Console.ReadLine(), out currentInput)
&& currentInput != EndOfInput)
{
allInput.Add(currentInput);
}
} while (currentInput != EndOfInput);
if (allInput.Count != 0)
Console.Write($"The largest number you entered was: {allInput.Max()}, and the smallest number you entered was: {allInput.Min()}.");
else
Console.WriteLine("You haven't entered any numbers.");
}
請注意,List<T>如果輸入的大小在運行時未知,最好使用可變大小的集合而不是常規陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/333941.html
標籤:C#
