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 trialMartyna Kurpinska
2,999 PointsAverage challenge
Hi,
I finished the Averager challenge, it works but I wonder if the code I've written is a good practice or bad practice, please let me know.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Averager_v2
{
class Program
{
static void Main()
{
var sumOfEntries = 0.0;
var sumLenght = 0.0;
while (true)
{
Console.WriteLine("Enter a number or type \"done\" to see the average:");
var userEntry = Console.ReadLine();
if (userEntry.ToLower() == "done")
{
break;
}
try
{
var userNumbers = double.Parse(userEntry);
sumOfEntries += userNumbers;
sumLenght += +1.0; // adds the numbers of entries
}
catch(FormatException)
{
Console.WriteLine("Please imput numbers");
continue;
}
}
var avrageOfEntry = sumOfEntries / sumLenght;
Console.WriteLine(avrageOfEntry);
Console.WriteLine("Goodbye");
System.Threading.Thread.Sleep(5000);//make the console wait before exiting
}
}
}
1 Answer
Steven Parker
231,248 PointsI'm not sure what course this was for, or what instructions and initial code you were given. But the few areas for possible improvement I see are:
- a "continue" is not needed if it's the last instruction in a loop
- "sumLenght" might have been spelled "sumLength" (it works as-is because it is used consistently)
- asking for and waiting on a keystroke to dismiss a window might be preferable to a fixed delay
These are all minor points, good job overall.