The C++ program below should return a stricly positive value. However, it returns 0.
What happens ? I suspect an int-double conversion, but I can’t figure out why and how.
#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;
}
Because you’ve supplied an initial value of
0, anint. Your code is internally equivalent to:While
result + 0.5 * 0.5produces the correct value (resultis promoted todoublein this expression), when that value is assigned back intoresult, it’s truncated (that expression is cast toint). You never get above1, so you see0.Give it an initial value of
0.0instead.