C# C# Basics (Retired) Perfect Wrap Up

Dominic Ratcliff
Dominic Ratcliff
9,425 Points

Averager challenge: did you do?

Below is my code, anyone else care to share how they coded this?

using System;

namespace Treehouse.Averager
{
  class Averager
  {
    static void Main()
    {
      var runningTotal = 0.0;
      var count = 0.0;

      while(true)
      {
      //Prompt user for number or done
      Console.Write("Enter a number or type \"done\" to see the average: ");
      string newNum = Console.ReadLine();

      if (newNum.ToLower() == "done")
      {
        break;
      }

      try
      {
        double toAdd = double.Parse(newNum);
        runningTotal += toAdd;
        count += 1;
      }

      catch (FormatException)
      {
        Console.WriteLine("That is not valid input.");
      }
      }

      Console.WriteLine("Average Rounded to 2 Places: " + Math.Round((runningTotal/count), 2));
  }

}
}
Alistair Mackay
Alistair Mackay
7,812 Points

I like the rounding to two decimal places, that's a nice touch.

I struggled through and came up with something like this, the total value isn't required but I liked the way it turned out in the end:

using System;

namespace Treehouse.CodeChallenges
{
  class Averager
  {
    static void Main()
    {

      var total = 0.0;
      var averageTotal = 0.0;
      var tryCount = 0;

      while(true)
      { 
        try
        {
          Console.WriteLine("Enter a number or type \"done\" to see the average:");
          Console.WriteLine("Entries: " + tryCount);
          Console.WriteLine("Running Total: " + total);
          Console.WriteLine("Average Total: " + averageTotal + "\n");

          var userInput = Console.ReadLine();

          // Exit Program command "done"
          if(userInput.ToLower().Equals("done"))
          {
            break;
          } 
          else
          {
            // Modify the values.
            double userValue = double.Parse(userInput);
            tryCount++;
            total += userValue;
            averageTotal = (total / tryCount); 
          }
        }        
        catch(FormatException)
        {
          Console.WriteLine("That is the wrong type of input, please try again.\n");
          continue;
        }
      }
    }
  }
}

my main problem was my tryCount variable would increment even if what the user input was the wrong type. This would mean my average value would be wrong going forward.

double userValue = double.Parse(userInput);

Parsing the input solved the problem as any input that wasn't a number after that point would throw a format exception before hitting the increment.

Good to see I was on the right path. Thanks for the share!

-PC