C++ 通过函数传递数组

C++ 通过函数传递数组,c++,arrays,mean,C++,Arrays,Mean,我试图通过一个函数传递一个简单的数组来计算平均值 int main() { int n = 0; // the number of grades in the array double *a; // the array of grades cout << "Enter number of scores: "; cin >> n; a = new double[n]; // the array of grades set

我试图通过一个函数传递一个简单的数组来计算平均值

int main()
{
    int n = 0; // the number of grades in the array
    double *a; // the array of grades

    cout << "Enter number of scores: ";
    cin >> n;

    a = new double[n]; // the array of grades set 
                       // to the size of the user input

    cout << "Enter scores separated by blanks: ";
    for(int i=0; i<n; i++)
    {
        cin >> a[i];
    }

    computeMean(a, n);
}

double computeMean (double values[ ], int n)
{
    double sum;
    double mean = 0;
    mean += (*values/n);
    return mean;
}
intmain()
{
int n=0;//数组中的等级数
double*a;//等级数组
cout>n;
a=新的双精度[n];//设置的等级数组
//到用户输入的大小
couta[i];
}
计算平均(a,n);
}
双计算平均值(双值[],整数n)
{
双和;
双平均值=0;
平均值+=(*值/n);
回归均值;
}

现在代码只取最后输入的数字的平均值

函数中没有循环。应该是这样的:

double sum = 0;
for (int i = 0; i != n; ++i)
  sum += values[i];

return sum / n;
我很惊讶您当前的版本只接受最后一个数字,它应该只接受第一个数字,因为
*值
值[0]
相同

更好的解决方案是使用惯用的C++:

return std::accumulate(values, values + n, 0.0) / n;

std::accumulate
应该可以做到这一点

#include <numeric>

double computeMean (double values[ ], int n) {
    return std::accumulate( values, values + n, 0. ) / n;
}
#包括
双计算平均值(双值[],整数n){
返回标准::累计(值,值+n,0.)/n;
}

这是一个家庭作业问题吗


您需要单步遍历数组中的所有值。您当前正在输出数组中的第一个数字除以项目数。

除非您应该将其称为
sum
,而不是
mean
,以避免混淆。请注意,传递整数
0
会使每个值和最终结果四舍五入。哦,好的一点-让我编辑它<代码>累积是一个奇怪的样本…:-)基于@Potatoswatter的评论,我想传递
0.0
意味着所有的计算都是在
双精度下完成的,如果你只想
浮点
精度,你需要
0.0f
浮点(0)
?(为了便于阅读,我建议使用第二种形式。)@Mike:accumulate
中第三个参数的类型决定了结果类型。将其保留为double,完成后将其分配给float;这对你没有坏处,你不妨利用你已经有的双打。首先对数组进行排序也是一个好主意。如果这是一个家庭作业问题,你应该将其标记为such@Mike是的,这是第一次,我说错了。