将十进制数近似为2位 [英] approximating decimal number to 2 places

查看:86
本文介绍了将十进制数近似为2位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



i想知道是否有可能将十进制数近似为2位?

当我保存一个值为0.3的变量时它会将其保存为0.30000000001

无论如何要防止这种情况或仅将变量保存为0.30?

谢谢。

Hi,
i want to know is it possible to approximate a decimal number to 2 places?
when i save a variable with a value 0.3 it saves it as 0.30000000001
anyway to prevent this or save the variable as 0.30 only?
thanks.

推荐答案

这是到期的关于浮点表示的本质,例如 double float

值存储为二进制值(精度有限) )和二进制比例因子。

0.3 不能用这种方式完全表示,所以最接近的可能值存储,在这种情况下 0.30000000001

您可以使用的格式字符串控制它的显示方式sprintf / printf /...

这也是涉及浮点值的比较通常应该包括一点 wiggle-room 的原因。 br />
例如,您不应该将某个值与正好等于0.3进行比较,但它们之间的差异小于某个可接受的容差。
This is due to the nature of floating-point representations, e.g. double or float.
The values are stored as a binary value (of limited precision) and a binary scale factor.
The value 0.3 cannot be represented exactly in this way, so the closest possible value is stored, in this case 0.30000000001.
You can control the way it is displayed with the formatting string of the sprintf/printf/...
This is also the reason that comparisons involving floating point values should usually include a little wiggle-room.
E.g., you shouldn't compare some value as exactly equal to 0.3 but that the difference between them is less than some acceptable tolerance.


每个计算机科学家应该知道关于浮点运算的知识 [ ^ ]。


0.3的值内部不能完全表示为浮点数。这就是你看到0.3000 ... 0001的原因。但是当在输出中打印该值时,您执行舍入操作,例如:

The value of 0.3 can internally not be represented exactly as a floating point number. That is the reason you see 0.3000...0001. But when printing that value in an output you perform a rounding operation, for example:
double x = 0.3;
printf ("x = %.2f\n", x);



将打印


will print

x = 0.30



与预期一致。所以printf为你做了舍入。



在内部处理浮点数时,我建议你不要试图绕它们。完成所有计算并在输出结果时在最后进行舍入。


just as expected. So printf does the rounding for you.

When dealing internally with floating point numbers I would suggest that you do not try to round them. Do all your calculation and do the rounding at the very end, when outputting the results.


这篇关于将十进制数近似为2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆