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;
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.