有人可以解释一下,在java中为什么0.6是<0.6f但是0.7is> = 0.7f [英] Can someone please explain me that in java why 0.6 is &lt;0.6f but 0.7is &gt;=0.7f

查看:653
本文介绍了有人可以解释一下,在java中为什么0.6是<0.6f但是0.7is> = 0.7f的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下,在java中为什么

Can someone please explain me that in java why

     if(0.6 <= 0.6f ) System.out.printf("true");
     else System.out.printf("false");

此PRINTS为真
但是

this PRINTS true but

    if(0.7 <= 0.7f ) System.out.printf("true");
    else  System.out.printf("false");

此PRINTS为假

是否相关当浮点数转换为双倍进行比较时,是否符合IEEE 754标准?

Is it related to IEEE 754 standards when floating point number is converted to double for comparision?

有人可以详细解释它的确切工作吗?

can someone explain it in detail the exact working?

推荐答案

当然 - 这只是理解 none 的0.6,0.6f,0.7和0.7f是 exact 值。它们是适当类型中最接近的可表示近似值。为这4个值存储的确切值是:

Sure - it's just a matter of understanding that none of 0.6, 0.6f, 0.7 and 0.7f are those exact values. They're the closest representable approximations in the appropriate type. The exact values which are stored for those 4 values are:

0.6f => 0.60000002384185791015625
0.6  => 0.59999999999999997779553950749686919152736663818359375
0.7f => 0.699999988079071044921875
0.7  => 0.6999999999999999555910790149937383830547332763671875

有了这些信息,很明显为什么你会得到你的结果。

With that information, it's clear why you're getting the results you are.

以另一种方式来思考,假设您有两个十进制浮点类型,一个具有4位精度,一个具有8位精度。现在让我们来看看如何表示1/3和2/3:

To think of it another way, imagine you had two decimal floating point types, one with 4 digits of precision and one with 8 digits of precision. Now let's look at how 1/3 and 2/3 would be represented:

1/3, 4dp => 0.3333
1/3, 8dp => 0.33333333
2/3, 4dp => 0.6667
2/3, 8dp => 0.66666667

因此,在这种情况下,精度较低的值小于1的较高精度值3,但这是2/3的逆转。对于 float double ,它只是二进制的。

So in this case the lower-precision value is smaller than the higher-precision one for 1/3, but that's reversed for 2/3. It's the same sort of thing for float and double, just in binary.

这篇关于有人可以解释一下,在java中为什么0.6是<0.6f但是0.7is> = 0.7f的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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