How do I make this code not include negative numbers in the total or average if
ID: 3794511 • Letter: H
Question
How do I make this code not include negative numbers in the total or average if they are entered? (C++)
For example, if you enter 4, 2, and -2, the average should not factor in the -2 and would be equal to 3. I want the code to factor in positive numbers only.
-----
#include
using namespace std;
int main()
{
int x, total = 0, count = 0;
cout << "Type in first value ";
cin >> x;
while (x != -1)
{
total += x;
count++;
cout << "Type in next value ";
cin >> x;
}
cout << "The average of these numbers is " << (double) total/count << endl;
cout << endl;
return 0;
}
Explanation / Answer
#include
using namespace std;
int main()
{
int x, total = 0, count = 0;
cout << "Type in first value ";
cin >> x;
while (x != -1)
{
if(x>=0)
{
total += x;
count++;
}
cout << "Type in next value ";
cin >> x;
}
cout << "The average of these numbers is " << (double) total/count << endl;
cout << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.