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;
}
#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;
}
Get Answers For Free
Most questions answered within 1 hours.