我是 C# 新手。我一直在致力于这个计划并进行研究,但一无所获。目标是让用户输入数字(多少由用户决定)。当他们输入0时,它将停止程序并显示输入的最小数字、输入的最大数字以及输入的所有数字的平均值。我没有收到任何错误,而且我收到了。如果有人可以请指出我正确的方向。
WriteLines 返回:
最小的数字是 0
最大数字是 0
平均值为:0
数量:5
这是我的代码:
int LOWEST =0;
int HIGHEST=0;
const int STOP = 0;
double average = 0;
int input;
int count = 0;
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
while (input != STOP)
{
for (int i=0; input != STOP; i++)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
count++;
var Out = new int[] { input };
LOWEST = Out.Min();
HIGHEST = Out.Max();
average = Out.Average();
if ((input > LOWEST) || (input < HIGHEST))
{
LOWEST = Out.Min();
}
if (input > HIGHEST)
{
HIGHEST = Out.Max();
}
}
}
Console.WriteLine("Lowest number is {0}", LOWEST);
Console.WriteLine("Highest number is {0}", HIGHEST);
Console.WriteLine("Average is {0}", average);
Console.WriteLine("Count: {0}", count);
Console.ReadLine();
每次运行时,您都会构造一个新的整数数组:
var Out = new int[] { input };
在此行之后,Out 包含一项:最后一个输入。呼唤Min
, Max
and Average
它将返回最后一个值。如果您结束程序,则为零。
您不想每次都创建一个新数组,而是创建一个List<int>
在程序的开头,然后将每个输入添加到其中。然后您可以使用整个值列表来计算Min
, Max
and Average
.
最终你可以将代码更改为如下所示:
const int STOP = 0;
int input = -1;
List<int> Out = new List<int>();
while (input != STOP)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
if (input == STOP) break;
Out.Add(input);
}
Console.WriteLine("Lowest number is {0}", Out.Min());
Console.WriteLine("Highest number is {0}", Out.Max());
Console.WriteLine("Average is {0}", Out.Average());
Console.WriteLine("Count: {0}", Out.Count);
Console.ReadLine();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)