[英]How to set floating point precision inside a variable
I am currently working a program where I need to calculate a rounded value to only 2 digits after a floating point. 我目前正在编写一个程序,我需要在浮点后计算舍入值到2位数。 Say, I have declared 说,我已经宣布了
float a;
If a = 3.555
then it would store a = 3.56
, rounding up. 如果a = 3.555
那么它将存储a = 3.56
,向上舍入。
For a = 3.423
, the value of a would be a = 3.423
, no change. 对于a = 3.423
,a的值将是a = 3.423
,没有变化。
I can do this to print output, but what I need to do when storing it into a variable and use that variable for some other calculation? 我可以这样做来打印输出,但是在将它存储到变量中并将该变量用于其他计算时我需要做什么?
If you need two digits after the decimal point, don't use floating point. 如果小数点后需要两位数,请不要使用浮点数。 Use a fixed point number instead. 请改用固定点数。 For example, just use an integer that's 100 times larger than the decimal number you want to represent. 例如,只使用比您想要表示的十进制数大100倍的整数。 Trying to fit a base 2 floating point number into rounding rules like this just isn't going to produce satisfactory results for you. 试图将基数为2的浮点数拟合到这样的舍入规则中,这对您来说不会产生令人满意的结果。
double d = 5000.23423;
d = ceil(d*100)/100;
cout << d << endl; // prints : 5000.24
double e = 5000.23423;
e = floor(e*100)/100;
cout << e << endl; // prints : 5000.23
你可以这样做:
a = roundf(a*100)/100;
How about 怎么样
#include <math.h>
int main ()
{
double a, f, i;
a = 3.436;
f= modf(a, &i);
a = i + roundf(f* 100.0) / 100.0;
return 0;
}
Operates on doubles but avoids scaling the whole number. 在双打上操作,但避免缩放整数。
Update : Added the missing division. 更新 :添加了缺失的部门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.