5

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

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

4

3 回答 3

10

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

#include <cmath>

y = floor(x * 10d) / 10d
于 2012-08-24T05:30:23.510 回答
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
}
于 2012-08-24T05:33:55.287 回答
0

你可以这样做:

int main()
{

    float a = 4212.12345f;
    float b = a * 10.0f;
    float c = ((int)b) / 10.0f;

    cout << c << endl;
    return 0;
}
于 2012-08-24T05:28:42.380 回答