通过函数传递数组
我试图通过函数传递一个简单的数组来计算平均值。
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;
}
现在,代码仅取最后输入的数字的平均值。
I'm trying to pass a simple array through a function to compute the 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
// 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;
}
Right now the code is only taking the mean of the last number that was inputted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的函数中没有循环。它应该是这样的:
我很惊讶你当前的版本只采用最后数字,它应该只采用第一个数字,因为
*values
与values[0]
相同。更好的解决方案使用惯用的 C++:
There's no loop in your function. It should be something like:
I'm surprised your current version only takes the last number, it should only take the first number, since
*values
is the same asvalues[0]
.A better solution uses idiomatic C++:
std::accumulate
应该可以解决问题。std::accumulate
should do the trick.这是家庭作业问题吗?
您需要逐步遍历数组中的所有值。您当前正在输出数组中的第一个数字除以项目数。
Is this a homework question?
You nead to step through all of the values in your array. You're currently outputting the first number in the array divided by the number of items.