C++,<int>浮点计算static_cast,可能丢失整数
c++, static_cast <int> of float point calculation and possible of losing integers
使用以下代码:
int ten{ 1 };
double zeroPnine{ 0.9 };
cout << ten - zeroPnine << endl; // 0.1
cout << (ten - zeroPnine) * 10 << endl; // 1
cout << static_cast <int>(ten - zeroPnine) << endl; // 0
cout << static_cast <int>((ten - zeroPnine) * 10 )<< endl; // 1
我希望最后一行输出1,但实际输出实际上是0,怎么会呢?
全输出:0.1
1
0
0
最好的建议是避免使用static_cast转换double。
如果您希望答案是整数,请在进行计算之前尝试将double转换为int。
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何理解C++标准N3337中的expr.const.cast子句8
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- C++Cast运算符过载
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址