Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many numbers higher than average [C++]

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
}
like image 419
Bostjan Bolovi Avatar asked May 13 '19 08:05

Bostjan Bolovi


1 Answers

This should be a comment, but I don't have enough reps :(

  • Change aboveAverage to void aboveAverage(int age[], int n, double avg)
  • Return avg from printAverage function
  • Change the last part of your main code to

    double avg;
    avg = printAverage(age, n);
    aboveAverage(age, n, avg);
    

Hope this helps!

like image 195
Art Avatar answered Oct 06 '22 01:10

Art