How many numbers higher than average [C++]

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;
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)

小智 10

这应该是一条评论,但我没有足够的代表:(

  • 更改aboveAveragevoid aboveAverage(int age[], int n, double avg)
  • avgprintAverage函数返回
  • main代码的最后一部分更改为

    double avg;
    avg = printAverage(age, n);
    aboveAverage(age, n, avg);
    
    Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 不要害怕,这是答案,不是评论。您还进行了5秒钟的操作,所以我删除了我的操作,并删除了UV ;-)可以建议OP在`cout &lt;&lt; num_over_average;`中也输出_endl_。 (3认同)