你如何在C++中舍入小数位?

Arm*_*ium 5 c++ floating-point precision

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

我知道setprecision(x)cout << precision(x).如果我想围绕整个浮点数,这两个都有效,但我只想将小数点四舍五入到十分之一位置.

mim*_*pus 10

还有另一个解决方案,不需要转换为int:

#include <cmath>

y = floor(x * 10d) / 10d
Run Code Online (Sandbox Code Playgroud)


Jes*_*ood 8

#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
}
Run Code Online (Sandbox Code Playgroud)