gpt4 book ai didi

c++ - 有多少数字高于平均值 [C++]

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:56:00 24 4
gpt4 key购买 nike

我用 30 个随机数填充了一个数组并计算了平均值。我想显示有多少数字高于平均值。我尝试制作一个函数“aboveAverage”并检查数字是否高于平均值,而不是仅仅增加计数“num_over_average++”。问题是我不知道如何将值“avg”从一个函数传递到另一个函数。

#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
}

最佳答案

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

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

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

希望这对您有所帮助!

关于c++ - 有多少数字高于平均值 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com