Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Basics (Retired) Perfect Wrap Up

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
231,084 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,021 Points

Thanks Steven Parker, You solved my problem too.