你如何在C++中四舍五入小数点

How do you round off decimal places in C++?

本文关键字:四舍五入 小数点 C++      更新时间:2023-10-16

我需要帮助将浮点值四舍五入到小数点后一位。

我知道setprecision(x)cout << precision(x)。如果我想对整个浮点值进行四舍五入,这两种方法都有效,但我只对将小数点四入到十分位感兴趣。

还有一种不需要强制转换为int的解决方案:

#include <cmath>
y = floor(x * 10d) / 10d
#include <cmath>
int main() {
    float f1 = 3.14159f;
    float f2 = 3.49321f;
    std::cout << std::floor(f1 * 10 + 0.5) / 10 << std::endl; 
    std::cout << std::floor(f2 * 10 + 0.5) / 10 << std::endl;
    std::cout << std::round(f1 * 10) / 10 << std::endl; // C++11
    std::cout << std::round(f2 * 10) / 10 << std::endl; // C++11
}

您可以这样做:

int main()
{
    float a = 4212.12345f;
    float b = a * 10.0f;
    float c = ((int)b) / 10.0f;
    cout << c << endl;
    return 0;
}