C++,<int>浮点计算static_cast,可能丢失整数

c++, static_cast <int> of float point calculation and possible of losing integers

本文关键字:cast 整数 int lt gt 计算 C++ static      更新时间:2023-10-16

使用以下代码:

    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。