C# C# Basics (Retired) Perfect Wrap Up

Eric Boissonneault
Eric Boissonneault
2,868 Points

The averager

Right now I know the program would crash if I entered anything else than done or a double but for the moment I'm trying to get the average. Here's my code, when I type done I get Nan as an average, I guess it is because it's trying to divide by 0 but I don't understand why.

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);
          continue;
        }
        else
        {
          var number = double.Parse(entry);
          numberTotal += + number;
          entryNumber += + 1.0;

        }

      }

    }
}

}

2 Answers

Steven Parker
Steven Parker
170,317 Points

You initialize average to NaN and never change it.

When you initialize average, you set it to numberTotal/entryNumber while both of those contain zero, so the result is NaN. Then for the rest of the program, you never assign it to anything else.

I'd guess you meant to add something like this to the end of the else block, but forgot:

            average = numberTotal / entryNumber;
Ashenafi Ashebo
Ashenafi Ashebo
15,017 Points

Thanks Steven Parker, You solved my problem too.