c – 为什么许多(旧)程序使用floor(0.5输入)而不是round(input)?

差异存在于返回值中,我认为这些输入可以打破平局,例如this code

int main()
{
    std::cout.precision(100);

    double input = std::nextafter(0.05, 0.0) / 0.1;
    double x1 = floor(0.5 + input);
    double x2 = round(input);

    std::cout << x1 << std::endl;
    std::cout << x2 << std::endl;
}

哪个输出:

1
0

但它们最终只是不同的结果,人们选择其首选的结果.我看到很多“旧的”C/C++程序使用floor(0.5输入)而不是round(输入).

有历史原因吗?最便宜的CPU?

解决方法:

在C 11中引入了std::round.在此之前,只有std::floor可用,所以程序员正在使用它.

上一篇:js随机数, 范围随机数


下一篇:从控制台输入n,利用format方法生成一个星号三角形