spexel
spexel

Reputation: 3

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

          }

        }
    }
}

Upvotes: 0

Views: 65

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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;

Upvotes: 1

Peter B
Peter B

Reputation: 1581

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.

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

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

Upvotes: 1

Related Questions