我想将总数累加为 double 而不是 float 。
vector<float> v;
....
double total = std::accumulate(v.begin(),
v.end(),
static_cast<double>(0.0));
//This compiles but I am not sure it is doing what I want
...
double total_ = std::accumulate<double>(v.begin(),
v.end(),
static_cast<double>(0.0)
);
// This doesnt compile, which leads me to believe the first accumulate
// is coercing the double(0.0) back to float.
有没有STL惯用简洁的写法
double total = 0.0;
for (int i = 0; i < v.size(); ++i) {
total += v[i];
}
只使用标准库。
我知道这不足以保持精度。
最佳答案
std::accumulate
中使用的累加类型从第三个参数的类型推导出来。字面量 0.0
是一个 double
,因此这使用 double
执行累加,无需显式转换:
double total = std::accumulate(v.begin(), v.end(), 0.0);
相当于
double sum = 0.0;
for (f : v) sum += f;
关于c++ - 使用 std::accumulate 以最佳精度添加 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22448747/