Why is the std::accumulate function showing the wrong sum of a vectorlt;doublegt;?(为什么 std::accumulate 函数会显示向量的错误总和lt;doublegt;?)
问题描述
考虑以下代码来添加 vector 的所有元素:
Consider the following code for adding all the elements of a 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 上编译并运行它时,我在终端得到输出
When I compile this on Cygwin on Windows and run it, I get the output at the terminal as
向量V的元素之和为9
accumulate 函数似乎将所有数字四舍五入并将它们相加,这将解释答案.
The accumulate function seems to be rounding down all the numbers and adding them up, which would explain the answer.
这是 Cygwin g++ 编译器有问题,还是我对 accumulate 函数的错误解释,用于将 double 的vector 相加?
Is this something wrong with the Cygwin g++ compiler, or my misinterpretation of the accumulate function for adding up a vector of doubles?
推荐答案
std::accumulate 声明如下:
template <typename InputIt, typename T>
T accumulate(InputIt first, InputIt last, T init);
std::accumulate 的第二个模板参数被推导出为 int 因为 0 是 int 类型.改为传递双精度值,例如 0.0.
The second template argument to std::accumulate is deduced as int because 0 is of type int. Pass a double instead, like 0.0.
这篇关于为什么 std::accumulate 函数会显示向量的错误总和<double>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 std::accumulate 函数会显示向量的错误总和<double>?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
