使用std::inner_product时,内部积为零
Zero inner product when using std::inner_product
下面的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
。
相关文章:
- 将函数类成员映射到类本身内部
- Boost Spirit,获取迭代器内部语义动作
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 内联函数中具有内部链接的全局变量
- 在函数内部的声明中初始化数组,并在外部使用它
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 卷曲bracers内部结构的声明
- 从函数角度看ID到文件路径的内部与外部映射
- spdlog标头仅与外部fmt一起使用.spdlog错误:'内部':不是'fmt'
- 如何在pugixml中获取节点的内部XML
- 使用C链接在函数内部创建C++模板
- 指针没有更新它在void函数内部指向的值
- 方法内部但循环仍得到预期的不合格id错误C++
- C++:具有内部链接的正向声明常量
- SDL_PollEvent() 无法捕获类函数内部SDL_QUIT?
- libcurl 和 DNS ttl 中的内部连接管理
- 如何修改 lambda 内部字符串的向量
- 如果我将嵌套映射作为多重映射的值,如何将值插入内部映射?
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 类内部和外部静态 constexpr 元组之间的差异