你如何舍入C ++中的小数位数? [英] How do you round off decimal places in C++?
本文介绍了你如何舍入C ++中的小数位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要帮助四舍五入浮点值到一个小数位。
I need help rounding off a float value to one decimal place.
我知道 setprecision(x)
和 cout< precision(x)
。如果我想绕整个浮动,这两个工作,但我只想把小数四舍五入到十分位置。
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.
推荐答案
还有另一个不需要转换为int的解决方案:
There's another solution which doesn't require casting to int:
#include <cmath>
y = floor(x * 10d) / 10d
这篇关于你如何舍入C ++中的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文