0

If you put a zero number between the entering numbers, it should stop and calculate the average just of entered numbers. Why it doesn't work?

static void Main(string[] args)
        {
            double num = 0, counter = 0;

            for (int i = 1; i <= 10; i++)
            {
                Console.Write("Enter the number:");
                num += int.Parse(Console.ReadLine());

                if (num == 0)
                    break;
                counter++;
            }

            double average = num / counter;

            Console.WriteLine("Average of the entered numbers is: {0}", average);
            Console.ReadLine();
        }

Any suggestions?

Edited by danuz: n/a

3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by danuz
0

You are adding the input value to num; then checking num. Therefore if you entered 5, 6, 7, 0. num would equal 18 when you checked it against 0. Try something like this:

...
int n = int.Parse(Console.ReadLine());
if(n == 0)
    break;
num += n;
...

Also, note that I used a int when comparing it to 0. Although an int value stored to a double should exactly equal an integer, it may not. It could be equal to something like 0.000000000000001. Floating point numbers can never be guaranteed to be exact. You should try and avoid exact comparisons of floating point numbers.

Edited by nmaillet: [code] tag mismatch

0

Num is never going to equal 0 once you start adding to it. I'd say set another variable to int.Parse(Console.ReadLine()) then add it to num after checking if it's 0.

for (int i = 1; i <= 10; i++)
{                
   Console.Write("Enter the number:");               
   int x = int.Parse(Console.ReadLine());                 
   if (x == 0)                    
      break;
   num += x;           
   counter++;            
}
0

Thank you!

Also thanks for an explanation.

Edited by danuz: /

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.