0

hi

Using while, write a program that keeps reading integers from user until he enters -1 then prints
the average of all entered numbers (-1 should be ignored).


this is my solution, but i dont know why he gives me wrong average?

#include<iostream>
using namespace std;

void main()
{
	double Number=0,average,sum=1,count;

	while(Number!=-1)
	{
		cout << "Enter a Number\n";
		cin >> Number;
		sum+=Number;
		count++;
		average=sum/count;
	}
	cout << "average= " << average<< endl;
}
2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Clinton Portis
0

1. you never initilize the 'count' variable.. it could be anything. (you should also do the same for 'average' as good practice)

2. you should decrement the count variable by 1 before using it in calculations in order to account for an extra loop iteration in the case of a -1 entry.

3. you should move line #14 outside of the loop.

Edited by Clinton Portis: n/a

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.