使用std::inner_product时,内部积为零

Zero inner product when using std::inner_product

本文关键字:内部 product std inner 使用      更新时间:2023-10-16

下面的C++程序应该返回一个严格的正值。但是,它返回0

会发生什么?我怀疑是int双转换,但我不知道为什么以及如何转换。

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
    vector<double> coordinates;
    coordinates.push_back(0.5);
    coordinates.push_back(0.5);
    coordinates.push_back(0.5);
     cout<<inner_product(coordinates.begin(), coordinates.end(), coordinates.begin(), 0)<<endl;
    return 0;
}

因为您提供了0的初始值,即int。您的代码在内部等效于:

int result = 0;
result = result + 0.5 * 0.5; // first iteration
result = result + 0.5 * 0.5; // second iteration
result = result + 0.5 * 0.5; // third iteration
return result;

虽然result + 0.5 * 0.5产生正确的值(在该表达式中,result被提升为double),但当该值被赋值回result时,它会被截断(该表达式被强制转换为int)。你永远不会超过1,所以你会看到0

给它一个初始值0.0

这是因为您提供了零作为整数常量。结果运算都是整数,因此最终值(0.75)也被截断为int

将零更改为0.0使其工作:

cout << inner_product(coord.begin(), coord.end(),coord.begin(), 0.0) << endl;

这在视频上产生0.75