Incorrect Output

closed account (3vX4LyTq)
I'm trying to find the mean of the vector, and then cout all values below the mean.

But it keeps cout as zero.

I think it may be because of the -1 to stop the loop. How else could I implement -1 to stop the loop?
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
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
int main() {
    vector<int> Grades;
    int input;
    float mean = 0;
    cout << "input grades and I will determine the average, and the print all below average grades. input -1 when you are ready.\n";
    while(input!=-1){
      cin >> input;
      Grades.push_back(input);
    }
    for(int i = 0; i < Grades.size();i++){
      mean = mean + Grades[i];
    }
    mean = mean / Grades.size();
    cout << "The average is " << mean << ". These grades are below the average:\n";
    for(int i = 0; i > Grades.size(); i++){
        if(Grades[i] <= mean){
          cout << Grades[i] << "\n";
        }
        if(i == Grades.size()){
          cout << "No grades were below the mean! Huh.";
        }
    }
}
  
Last edited on
first, you might put an if statement to protect your data:

if(input != -1)
grades.push_back(input);

prevents putting a -1 in your data.

otherwise, use of a sentinel is fine. There are other ways, but not really that much "better".

I suspect the issue here is that you forgot to value input.
define it as int input = 0 to be sure your while loop executes the first time.

if these 2 things don't help, ill look again
closed account (3vX4LyTq)
jonnin - thank you for your help. I accidently did greater than when I meant to put a less than. however, that wouldn't have worked if you didn't tell me to add " if(input != -1) "

Thanks :)

jared
Topic archived. No new replies allowed.