I'm supposed to be making a program to take 5 ages, calculate the average, then display how many of the ages are above the average and how many are below. Easy, I thought. However, for some reason, no matter what I do, the if statement to check if the current ages[] element is less than the average always holds true and the if statement to check if the current ages[] element is more than the average always hold false, and I can't for the life of me figure out why. Maybe it's because it's 3:30am here and my brain has gone to mush.
I have tried adding in a variable called age = ages[j] for every iteration. I have also tried swapping around the above and below if statements however that also doesn't change anything.
#include <iostream>
using namespace std;
void main() {
int ages[5];
int total = 0;
int average = 0;
int above = 0;
int below = 0;
for (int i = 0; i < 5; i++) {
cout << "Enter an age.";
cin >> ages[i];
cout << ages[i];
total += ages[i];
}
average = total / 5;
for (int j = 0; j < 5; j++) {
if (ages[j] >> average) {
cout << ages[j];
above++;
}
else if (ages[j] << average) {
cout << average;
cout << ages[j];
below++;
}
}
cout << "The average age is " << average << "." << endl;
cout << above << " ages are above the average age." << endl;
cout << below << " ages are below the average age." << endl;
}
I expect the output of "The average age is (average)" "x ages are above the average age." "y ages are above the average age"
Instead I get: "The average age is (average)" "0 ages are above the average age." "5 ages are below the average age."
You are using bitshifts instead of greater-than/less-than
if (ages[j] > average)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.