Bos*_*ovi 5 c++ arrays numbers average
I filled an array with 30 random numbers and calculated average. I want to display how many numbers are higher than the average. I tried making a function "aboveAverage" and check if the numbers are higher than the average and than just increase the count "num_over_average++". The problem is I don't know how to pass a value "avg" from function to another function.
#include <iostream>
#include <ctime>
using namespace std;
const int n = 30;
void fillArray(int age[], int n) {
    srand(time(NULL));
    for (int index = 0; index < n; index++) {
        age[index] = (rand() % 81) + 8;     
    }
}
void printArray(int age[], int n) {
    for (int index = 0; index < n; index++) {
        cout << age[index] << endl;
    }
}
double printAverage(int age[], int n) {
    double sum;
    double avg = 0.0;
    for (int i = 0; i < n; i++) {
        sum = sum + age[i];
    }
    avg = ((double) sum) / n;
    cout <<  avg << endl;
    return avg;
}
void aboveAverage(int age[], int n) {
    double avg;
    int num_over_average = 0;
    for(int i = 0; i < n; i++){
            if(age[i] > avg) {
                num_over_average++;
            }
        }
    cout<<num_over_average;
}
int main(int argc, char *argv[]) {
    int age[n];
    fillArray(age, n);
    cout << "array: " << endl;
    printArray(age, n);
    cout << endl;
    aboveAverage(age, n);
    //example: Days above average: 16
}
小智 10
这应该是一条评论,但我没有足够的代表:(
aboveAverage为void aboveAverage(int age[], int n, double avg)avg从printAverage函数返回将main代码的最后一部分更改为
double avg;
avg = printAverage(age, n);
aboveAverage(age, n, avg);
希望这可以帮助!