I'm trying to create a program where the user can enter numbers over and over, until they enter a negative number, which will end the program. It will also calculate the average of the positive numbers that were entered.
#include <iostream>
usingnamespace std;
double average();
int main(){
char answer;
cout << "Average calculator." << endl;
cout << endl;
cout << "Enter a stream of positive numbers (0 or above)." << endl;
cout << "Enter a negative number to indicate you are finished." << endl;
int value;
cin >> value;
while (value >= 0)
{average();
if (value >= 0)
{cout << "The average is: " << average() << endl;
cout << endl;
cout << "Do you want to compute another average (y or n)?" << endl;
cin >> answer;}
if (answer == 'y')
{cout << "Enter a stream of positive numbers (0 or above)." << endl;
cout << "Enter a negative number to indicate you are finished." << endl;
average();}
if (answer == 'n')
{return 0;}
}
}
double average(){
int value;
int count = 0;
int sum = 0;
double average;
do
{cin >> value;
sum += value;
count++;
average = sum / count;
return average;
if (value < 0)
{return 0;}
} while (value >= 0);
}
So far, the program just allows me to input numbers, but it doesn't not show the average or end the program when I enter a negative number. Please help!
There is no need to call average function after the: while(value>=0).
Also, the reason why it runs without asking the user whether he wants to compute more is because, if he enters 'y' at the first instance, answer is always equal to 'y'. So you must reset it(maybe with answer=0) at the end or beginning of the loop.
#include <iostream>
usingnamespace std;
double average();
int main(){
char answer;
cout << "Average calculator." << endl;
cout << endl;
cout << "Enter a stream of positive numbers (0 or above)." << endl;
cout << "Enter a negative number to indicate you are finished." << endl;
int value;
cin >> value;
average();
while (value >= 0)
{
if (value >= 0)
{cout << "The average is: " << average() << endl;
cout << endl;
cout << "Do you want to compute another average (y or n)?" << endl;
cin >> answer;}
if (answer == 'y')
{cout << "Enter a stream of positive numbers (0 or above)." << endl;
cout << "Enter a negative number to indicate you are finished." << endl;
average();}
if (answer == 'n')
{return 0;}
answer = 0;
}
}
double average(){
int value;
int count = 0;
int sum = 0;
double average;
do
{cin >> value;
sum += value;
count++;
average = sum / count;
return average;
if (value < 0)
{return 0;}
} while (value >= 0);
}
Why doesn't this part loop? It ends after I enter y.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
do
{
counter++;
cout << "Enter a stream of positive numbers (0 or above)." << endl;
cout << "Enter a negative number to indicate you are finished." << endl;
cin>>value;
if (value < 0)
{cout<<"The average is: "<<calcAverage(sum,counter,value)<<endl<<endl;
cout << "Do you want to compute another average (y or n)?" << endl;
cin >> answer;
value = 0;
} while(value >= 0);