我一直致力于一个项目,可以检测您输入的最小数字,并可以找到它的平均值。我创建了一个循环,使代码永远进行,直到你输入:“退出”。但由于某种原因,控制台提供的答案始终是您输入的第一个号码。请帮我查一下bug和解决方案,谢谢!
以下是原始代码:
static void Main(string[] args)
{
List<double> nums = new List<double>();
bool quit = false;
while (!quit)
{
Console.WriteLine("Enter as many numbers as you want, but leave a space between them, if you want to quit, please enter 'Quit'.");
string foo = Console.ReadLine();
if (foo == "Quit")
{
quit = true;
return;
}
string[] tokens = foo.Split(' ');
double oneNum;
foreach (string s in tokens)
{
if (double.TryParse(s, out oneNum))
{
nums.Add(oneNum);
}
else
{
Console.WriteLine("You have inputed invalid number, please try again!");
break;
}
double smallestValue = nums[0];
double num = 0;
for (int i = 0; i < nums.Count; i++)
{
num = nums[i];
if (smallestValue > num)
smallestValue = num;
}
double mean = 0;
double sum = 0;
for (int i = 0; i < nums.Count; i++)
{
sum = sum + nums[i];
}
mean = sum / nums.Count;
Console.WriteLine("The smallest number amoung the intergers is {0}, and their average is {1}.", smallestValue, mean);
Console.ReadLine();
}
}
}
}
}
答案 0 :(得分:0)
您在此循环结束时缺少结束大括号(}
)。
foreach (string s in tokens)
{
if (double.TryParse(s, out oneNum))
{
nums.Add(oneNum);
}
else
{
Console.WriteLine("You have inputed invalid number, please try again!");
break;
}
如果没有关闭括号,以下所有计算都被认为是在该循环中!由于代码包含对Console.ReadLine()
的调用,因此当您仅完成循环的第一次迭代时,看起来已经完成了计算。