我在树屋做了这个挑战,我无法弄清楚为什么我会得到" Nan"当我输入"完成"。我想这是因为它试图划分,但我不明白为什么它会保持在0。无论如何,到目前为止我的代码是:
using System;
namespace averager
{
class Program
{
static void Main()
{
var numberTotal = 0.0;
var entryNumber = 0.0;
var average = (numberTotal/entryNumber);
while(true)
{
// Prompt user to enter a number or enter "done" to see the average
Console.Write("Enter a number or type \"done\" to see the average: ");
var entry = Console.ReadLine();
if(entry.ToLower() == "done")
{
Console.WriteLine("The average is: " + average);
break;
}
try
{
var number = double.Parse(entry);
numberTotal += + number;
entryNumber += + 1.0;
}
catch(FormatException)
{
Console.WriteLine("That is not a valid input");
continue;
}
}
}
}
}
答案 0 :(得分:1)
Console.WriteLine("The average is: " + average);
您在程序开始时设置平均值,但在用户输入值后从未实际设置它。如果更改上面的行以实际运行计算:
Console.WriteLine("The average is: " + numberTotal/entryNumber);
您将看到预期的结果
答案 1 :(得分:1)
看!您刚刚分配了avegare 一次:
// 0.0 / 0.0 == NAN
var average = (numberTotal/entryNumber);
并且从那时起就不要改变它:
var number = double.Parse(entry);
//what do you mean by unary + here?
numberTotal += + number;
//what do you mean by unary + here?
entryNumber += + 1.0;
// average is NOT updated
最后,您输出的初始average
是NAN
:
Console.WriteLine("The average is: " + average);
添加average
计算
var number = double.Parse(entry);
numberTotal += number;
entryNumber += 1.0;
//TODO: do not forget to change average
average = numberTotal / entryNumber;
答案 2 :(得分:0)
在变量变化之前计算平均值,并且仍然为零。永远不会再计算平均值。读入新值后,您应该再次计算平均值。