简体   繁体   中英

return the average, very simple C# code

I'm doing this challenge on Treehouse and I can't figure out why I get "Nan" when I type "done". I guess it's because it tries to divide but I don't understand why it stays at 0. Anyways here's my code so far:

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;
            }

          }

        }
    }
}
Console.WriteLine("The average is: " + average);

you set average at the start of the program, but never actually set it after the user has inputted values. If you change the above line to actually run the calculation:

Console.WriteLine("The average is: " + numberTotal/entryNumber);

you will see expected results

Look! You've just assigned the avegare once :

 // 0.0 / 0.0 == NAN
 var average = (numberTotal/entryNumber);

and don't change it ever since:

 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

finally, you output the initial average which is NAN :

  Console.WriteLine("The average is: " + average);

Add average computation

 var number = double.Parse(entry);
 numberTotal += number;  
 entryNumber += 1.0;

 //TODO: do not forget to change average
 average = numberTotal / entryNumber;

The average is calculated before the variables are changed, and are still zero. The average is never calculated again. After you read in the new values, you should calculate the average again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM