c++ - C ++“<”小于运算符未按预期工作
问题描述
我是 C++ 新手,我只是偶然发现了这个问题。我在下面创建了一个函数,用于将浮点数舍入到小数点后 2 位。
float rounding(float x)
{
float t = static_cast<int>(x * 100 + 0.5);
return t / 100;
}
现在在下面使用这个函数main
。
int main()
{
if (rounding(10.456) < 10.46)
std::cout << "LESS" << std::endl;
else
std::cout << "NOT LESS" << std::endl;
}
预期输出不是 LESS,因为rounding(10.456) = 10.46
但收到的输出是LESS。我也试过打印rounding(10.456)
,结果是10.46。但它与<
操作员的预期不同。
为什么我的程序会这样,我该如何解决?
解决方案
推荐阅读
- c# - 如何动态创建视图 MVC
- java - Apache POI - 如何获取与 Excel 中显示的格式完全相同的日期?
- bash - 如何编写 for 循环以将数据提取到新创建的文件?
- java - 使用子类对象的继承方法返回父类变量
- javascript - 开玩笑 getReversedNavigationSections of null
- php - 为什么 curl 抛出异常,错误 35
- ios - 如何在 Corespotlight 搜索中显示消息和视频按钮?
- jquery - 如何将剑道网格层次结构的两个孩子放入选项卡?
- html - 将 Twitter 提要嵌入网站,但显示在轮播中
- python - 从 Quantlib BachelierSwaption 价格中检索 Black vol