七月的风八月的雨,卑微的我喜欢遥远的你
你还未来怎敢老去,未来的我和你奉陪到底
你若同意我一定去,可你并不在意我的出席
你的过去无法参与,但我还是喜欢你
-----------------------------------------------------------------------------------《遥远的你》
七月,欢喜交加的一月,中旬通过一家公司的面试,但是offer要走北京总部的流程,大概两周左右,HR让我等,等了快二十天了,不敢再等了。抓着七月的尾巴,疯狂投了一波简历,两天内成功拿到offer,也算是找到了第一份实习。今天看到有这样一个面试题:
System.out.println(0.1*3 == 0.3);
输出什么???
答案是:
false
为此我专门跑了一把程序,得到的结果如下:
1 * 0.1 = 0.1
1 * 0.2 = 0.2
1 * 0.3 = 0.3
1 * 0.4 = 0.4
1 * 0.5 = 0.5
1 * 0.6 = 0.6
1 * 0.7 = 0.7
1 * 0.8 = 0.8
1 * 0.9 = 0.9
2 * 0.1 = 0.2
2 * 0.2 = 0.4
2 * 0.3 = 0.6
2 * 0.4 = 0.8
2 * 0.5 = 1.0
2 * 0.6 = 1.2
2 * 0.7 = 1.4
2 * 0.8 = 1.6
2 * 0.9 = 1.8
3 * 0.1 = 0.30000000000000004
3 * 0.2 = 0.6000000000000001
3 * 0.3 = 0.8999999999999999
3 * 0.4 = 1.2000000000000002
3 * 0.5 = 1.5
3 * 0.6 = 1.7999999999999998
3 * 0.7 = 2.0999999999999996
3 * 0.8 = 2.4000000000000004
3 * 0.9 = 2.7
4 * 0.1 = 0.4
4 * 0.2 = 0.8
4 * 0.3 = 1.2
4 * 0.4 = 1.6
4 * 0.5 = 2.0
4 * 0.6 = 2.4
4 * 0.7 = 2.8
4 * 0.8 = 3.2
4 * 0.9 = 3.6
5 * 0.1 = 0.5
5 * 0.2 = 1.0
5 * 0.3 = 1.5
5 * 0.4 = 2.0
5 * 0.5 = 2.5
5 * 0.6 = 3.0
5 * 0.7 = 3.5
5 * 0.8 = 4.0
5 * 0.9 = 4.5
6 * 0.1 = 0.6000000000000001
6 * 0.2 = 1.2000000000000002
6 * 0.3 = 1.7999999999999998
6 * 0.4 = 2.4000000000000004
6 * 0.5 = 3.0
6 * 0.6 = 3.5999999999999996
6 * 0.7 = 4.199999999999999
6 * 0.8 = 4.800000000000001
6 * 0.9 = 5.4
7 * 0.1 = 0.7000000000000001
7 * 0.2 = 1.4000000000000001
7 * 0.3 = 2.1
7 * 0.4 = 2.8000000000000003
7 * 0.5 = 3.5
7 * 0.6 = 4.2
7 * 0.7 = 4.8999999999999995
7 * 0.8 = 5.6000000000000005
7 * 0.9 = 6.3
8 * 0.1 = 0.8
8 * 0.2 = 1.6
8 * 0.3 = 2.4
8 * 0.4 = 3.2
8 * 0.5 = 4.0
8 * 0.6 = 4.8
8 * 0.7 = 5.6
8 * 0.8 = 6.4
8 * 0.9 = 7.2
9 * 0.1 = 0.9
9 * 0.2 = 1.8
9 * 0.3 = 2.6999999999999997
9 * 0.4 = 3.6
9 * 0.5 = 4.5
9 * 0.6 = 5.3999999999999995
9 * 0.7 = 6.3
9 * 0.8 = 7.2
9 * 0.9 = 8.1
这个结果既是情理之中,又在意料之外啊 ^ - ^。
再来一道:
System.out.println("1.0 - 0.1 = "+(1.0-0.1)+" ===> "+(1.0-0.1==0.9));
System.out.println("1.0 - 0.1f = "+(1.0-0.1f)+" ===> "+(1.0-0.1f==0.9));
System.out.println("1.0f - 0.1f = "+(1.0f-0.1f)+" ===> "+(1.0f-0.1f==0.9));
System.out.println("1.0f - 0.1f = "+(1.0f-0.1f)+" ===> "+(1.0f-0.1f==0.9f));
输出什么呢?
答案依次是:
1.0 - 0.1 = 0.9 ===> true
1.0 - 0.1f = 0.8999999985098839 ===> false
1.0f - 0.1f = 0.9 ===> false
1.0f - 0.1f = 0.9 ===> true
注意:没有 f 的即是double型,有 f 的是float型。
一定要注意,java中下面声明是会报错的,因为0.1是double型,需要加(double)强制转换类型。
float a = 0.1;
最后一句话共勉,你的努力终究会给你带来回报,加油!!!