如何设置浮点precision一个变量中 [英] How to set floating point precision inside a variable
问题描述
我目前工作的一个程序,我需要一个浮点后,计算一个圆形的值只有2位。
我说,我已经声明
I am currently working a program where I need to calculate a rounded value to only 2 digits after a floating point. Say, I have declared
float a;
如果 A = 3.555
那就存储 A = 3.56
,围捕。
有关 A = 3.423
的价值将是 A = 3.423
,没有任何变化。
For a = 3.423
, the value of a would be a = 3.423
, no change.
我能做到这一点,打印输出,但我需要它存储到一个变量时做的,使用该变量其他一些计算?
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?
推荐答案
如果您需要小数点后两位数字,不要使用浮点。使用固定的点数来代替。例如,只需要使用一个整数,它比你想重新present十进制数大100倍。试图将基地2浮点数四舍五入成这样的规则,只是不会产生令人满意的结果给你。
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. Trying to fit a base 2 floating point number into rounding rules like this just isn't going to produce satisfactory results for you.
这篇关于如何设置浮点precision一个变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!