计算数组的均值函数翻倍[]采用累积 [英] Function for calculating the mean of an array double[] using accumulate
问题描述
这必须是每个人都拥有一个code段某处最常用的功能,但其实我已经花了不低于1.5小时去找它的SO以及对其他的C ++网站,并没有找到一个解决办法。
我想为计算的平均双阵列[]
使用功能即可。我想数组传递给函数作为参考。现在有成千上万的例子,平均在一个main()循环计算,但是我期待的是我可以把外部文件和以后的任何时间使用它的功能。
到目前为止,这里是我的最新版本,是什么让编译错误:
双mean_array(double数组[])
{
诠释计数= sizeof的(阵列)/的sizeof(数组[0]);
双总和=累加(数组,数组+计数,0);
返回(双)总和/计数;
}
编译错误是:
错误C3861:'厚积薄发':标识符找不到
块引用>你能告诉我如何解决这个功能呢?这是什么编译错误是什么意思?
如果我用
的std ::积累
(在已定义的使用命名空间std
),然后我得到的以下错误:收集:是不是'性病'中的一员
收集:标识未找到为什么要为收集性病的还不是会员?
的 PS:我知道我能做到'之和+ =阵列[I]的方式,而不是用累加的,但我想知道这里发生了什么,我怎么可以让我的例子中工作
解决方案尝试添加
的#include<数字>
这将在'的std ::收集功能带给你要寻找的。 P>
进一步说,你要去有问题找出你的数组中元素的个数。实际上,阵列不能被传递给函数,希望的功能将能够知道数组的大小。它会衰减到一个指针。因此,你的
计数
计算将是错误的。如果您希望能够通过实际指定大小的数组,你必须使用一个模板函数。模板< INT N'GT;
双mean_array(双(&安培;数组)[N])
{
返回的std ::累加(数组,数组+ N,0.0)/(双)(N);
}It must be the most common function for what everyone has a code snippet somewhere, but I have actually spent no less than 1.5 hour searching for it on SO as well as on other C++ sites and have not found a solution.
I would like to calculate the mean of a
double array[]
using a function. I would like to pass the array to the function as a reference. There are millions of examples where the mean is calculated in a main() loop, but what I am looking for is a function what I can put in an external file and use it any time later.So far, here is my latest version, what gives a compile error:
double mean_array( double array[] ) { int count = sizeof( array ) / sizeof( array[0] ); double sum = accumulate( array, array + count, 0 ); return ( double ) sum / count; }
The compile error is:
error C3861: 'accumulate': identifier not found
Can you tell me how to fix this function? What does that compile error mean?
If I use
std::accumulate
(over the already definedusing namespace std
), then I get the following error:'accumulate' : is not a member of 'std' 'accumulate': identifier not found
Why is 'accumulate' not a member of 'std'?
p.s.: I know I can do 'sum += array[i]' way and not use accumulate, but I would like to understand what is happening here and how can I make my example work.
解决方案Try to add
#include <numeric>
It will bring in the 'std::accumulate' function you're looking for.
Going further, you're gonna have a problem to find out the number of elements in your array. Indeed, an array cannot be passed to a function in the hope that the function will be able to know the size of the array. It will decay to a pointer. Therefore, your
count
calculation will be wrong. If you want to be able to pass an actual size specified array, you have to use a templated function.template <int N> double mean_array( double ( & array )[N] ) { return std::accumulate( array, array + N, 0.0) / (double)(N); }
这篇关于计算数组的均值函数翻倍[]采用累积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!