首页 > 解决方案 > 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++comparisonoperator-keyword

解决方案


推荐阅读