C++ 你如何舍入C++中的小数位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12103514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you round off decimal places in C++?
提问by Arminium
I need help rounding off a float value to one decimal place.
我需要帮助将浮点值四舍五入到一位小数。
I know setprecision(x)
and cout << precision(x)
. Both of which work if I wanted to round the entire float, but I am only interested in rounding the decimals to the tenths place.
我知道setprecision(x)
和cout << precision(x)
。如果我想将整个浮点数四舍五入,这两种方法都可以使用,但我只对将小数四舍五入到十分之一感兴趣。
回答by mimicocotopus
There's another solution which doesn't require casting to int:
还有另一种不需要转换为 int 的解决方案:
#include <cmath>
y = floor(x * 10d) / 10d
回答by Jesse Good
#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
}
回答by alvmed
You can do this:
你可以这样做:
int main()
{
float a = 4212.12345f;
float b = a * 10.0f;
float c = ((int)b) / 10.0f;
cout << c << endl;
return 0;
}