How to read only positive integers and ignore the negative ones

I'm trying to write a program that will ask for 10 grades and return the average. If the grade is "-1", I want to ignore it and not compute the grade for it. The first part is working fine, but do you have any suggestions on how to ignore the negative grades?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <iomanip>
using namespace std;


const int SIZE = 10; //Make the SIZE unchangable
void getGrade(float listGPA[]);
double average(float listGPA[]);

int main()
{
   float listGPA[SIZE] = {};
   getGrade(listGPA);
   cout << "Average Grade: " << average(listGPA) << "%" <<  endl;

   return 0;
      

}
void getGrade(float listGPA[])
{

   for (int iGPA = 0; iGPA < SIZE; iGPA++)
   {
      cout << "Grade " << iGPA + 1 << ": "; 
      cin >> listGPA[iGPA];
   }
   
}

double average(float listGPA[])
{
   int sum = 0;

   for (int i = 0; i < SIZE; i++)
   {
      sum += listGPA[i];
   }
   return sum / 10.0;
}
Last edited on
The number of grades that count will be different from the number in the array:
1
2
3
4
5
6
7
8
9
10
11
12
13
double average(float listGPA[])
{
   int sum = 0;
   unsigned count = 0; // number of grades to count
   for (int i = 0; i < SIZE; i++)
   {
      if (listGPA[i] >= 0) {
         sum += listGPA[i];
         ++count;
      }
   }
   return sum / count;
}
thanks,

It was returning floating point exception, but with a few adjustments I was able to make it work.
Oh smack me silly. Speaking of floating point exceptions, line 12 of my example does integer division instead of floating point. So it should be return static_cast<double>(sum) / count;

That'll teach me to post code without testing it. :(
Topic archived. No new replies allowed.