考虑以下用于添加vector的所有元素的代码
#include<iostream>
#include<algorithm>
#include<numeric>
#include<vector>
using namespace std;
int main(void)
{
std::vector<double> V;
V.push_back(1.2);
V.push_back(3.6);
V.push_back(5.6);
double sum = accumulate(V.begin(),V.end(),0);
cout << "The sum of the elements of the vector V is " << sum << endl;
return 0;
}当我在Windows上的Cygwin上编译并运行它时,我在终端得到如下输出
向量V的元素之和是9
accumulate函数似乎正在对所有数字进行四舍五入并将它们相加,这就解释了答案。
这是Cygwin g++编译器的错误,还是我对用于添加vector of doubles的accumulate函数的误解?
发布于 2013-12-23 09:25:09
std::accumulate是这样声明的:
template <typename InputIt, typename T>
T accumulate(InputIt first, InputIt last, T init);std::accumulate的第二个模板参数被推导为int,因为0的类型为int。取而代之的是传递一个双精度值,比如0.0。
发布于 2013-12-23 09:24:32
将0更改为0.0。然后它会为我获取10.4。虽然容器是double,但由于传递给std::accumulate的初始参数,类型推导为int。因此,为容器分配了int值。
发布于 2013-12-23 09:27:20
从std::accumulate函数返回的值是一个整数,而不是一个双精度数,原因如下:
double sum = accumulate(V.begin(), V.end(), 0);
// ^-- Integer!由C++编译器完成的模板参数推断使accumulate函数的返回类型与init参数相同,在本例中为整数。因此,返回值将四舍五入为最接近的整数。当返回值被赋值为sum时,返回值将被隐式转换回双精度值。
要解决此问题,您可以简单地将零作为双精度值(即0.0)进行传递。
https://stackoverflow.com/questions/20735841
复制相似问题