我有一个程序要求用户输入任意数量的浮点数。我需要在控制台上输出这些值并应用以下返回值:我需要找到数字的总和
我无法弄清楚如何获得输出
这是我目前的代码:
bool charactersFound = false;
List<float> allNumbers = new List<float>();
while (charactersFound == false)
{
while (charactersFound == false)
{
String textEntered = Console.ReadLine();
if (textEntered.ToUpperInvariant().Contains("STOP"))
{
charactersFound = true;
}
break;
allNumbers.Add(float.Parse(textEntered));
}
float max = array.Max();
float min = array.Min();
float total = array.Sum();
}
如何在控制台上将上述每个值输出到不同的行?
答案 0 :(得分:0)
提取方法(在您的情况下为inputArray
),请不要将所有内容都放在单个例程中:
private static float[] inputArray() {
List<float> list = new List<float>();
while (true) {
string textEntered = Console.ReadLine();
if (textEntered.ToUpperInvariant().Contains("STOP"))
return list.ToArray();
if (float.TryParse(textEntered, out var item))
list.Add(item);
else
Console.WriteLine($"\"{textEntered}\" is not a floating point value, ignored");
}
}
...
float[] array = inputArray();
//TODO: you may want to check here if array is not empty
if (array.Length == 0)
Console.WriteLIne("The array is empty");
else {
Console.WriteLine($"[{string.Join(", ", array)}]");
Console.WriteLine($" Max = {array.Max()}");
Console.WriteLine($" Min = {array.Min()}");
Console.WriteLine($" Total = {array.Sum()}");
}