2012-08-24 100 views
4

我需要幫助將浮點值四捨五入到小數點後一位。我知道setprecision(x)cout << precision(x)。如果我想要整個浮點數的話,兩者都有效,但我只想將小數點四捨五入到十分之一。如何在C++中舍入小數位?

+0

[四捨五入至小數點後第二位點]的可能重複(HTTP ://stackoverflow.com/questions/4030190/rounding-to-the-second-decimal-spot) – jogojapan

回答

10

還有另一種解決方案,它不需要鑄造爲int:

#include <cmath> 

y = floor(x * 10d)/10d 
0

你可以這樣做:

int main() 
{ 

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

    cout << c << endl; 
    return 0; 
} 
7
#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 
}