EXERCISE 11
Write a program that asks the user to type a positive integer. When the user types a negative value the program writes ERROR and asks for another value.
When the user types 0, that means that the last value has been typed and the program must write the average of the positive integers.
If the number of typed values is zero the program writes 'NO AVERAGE'.
This is what i've got:
#include <iostream>
using namespace std;
int main ()
{
int a, b, c;
double d;
while (a != 0) {
cout << "Give number: ";
cin >> a;
if (a < 0)
cout << "ERROR !!\n";
else
b = b + a;
c++;
}
d = b / c;
if (c < 1)
cout << "NO AVERAGE\n";
else
cout << "The average is: " << d << "\n";
system("pause");
return 0;
}
Everything seems to be working up to the point where it has to show the average, which gives completely the wrong answer.
Can someone help me, what am i doing wrong?
I know the solution is on the site, but i'd like to get there with my version.
Your problem: b and c are not initialized, so there is an undefined value on them.
Some considerations: name your variables better, like number, total, count and average. b / c returns an int, since both variables are ints. To make it do a normal division, cast either one to float or double (double is better, since it's the type you assign the result to).
this is my code as it is now and seems to be working:
int main ()
{
int number;
double sum = 0, count = 0, average;
while (number != 0) {
cout << "Give number: ";
cin >> number;
if (number < 0)
cout << "ERROR !!\n";
else
sum = sum + number;
count++;
if (number < 1)
count--;
}
average = sum / count;
if (count < 1)
cout << "NO AVERAGE\n";
else
cout << "The average is: " << average << "\n";
system("pause");
return 0;
}