Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote