为什么第一个代码中if()
的正文执行虽然第二个代码中if()
的正文不执行
工作
double num1 = 0.2;
double num2 = 0.2;
double num3 = num1 + num2;
if (num3 == 0.4)
{
MessageBox.Show("1st");
}
不工作
double num1 = 0.1;
double num2 = 0.2;
double num3 = num1 + num2;
if (num3 == 0.3)
{
MessageBox.Show("2nd");
}
答案 0 :(得分:2)
原因
机器使用二进制语言当它将数字转换为二进制时,转换回十进制数值得到改变,由于某些数字无法完全转换为二进制
当你转换0.1 into base 2 (binary)
时,你会得到小数点后的重复模式,
喜欢 1/3 in base 10 ; 1/3=0.333333333333333333333333333333333..........
&从来没有得到确切的价值
因此,您无法使用常规浮点方法获取每个数字的精确值。
示例(转换模式)
0.1二进制模式......
Source: Why 0.1 Does Not Exist In Floating-Point
0.1转换 0.1 is one-tenth, or 1/10. To show it in binary
您可以看到100
正在重复间隔作为输出为1001
如图所示
Source: Why 0.1 Does Not Exist In Floating-Point
第二个代码片段{0.1 + 0.2的答案与实际值0.3不相同}
--------------------------------------------------------------
Actual {Answer of 0.1+0.2 Is not Same as actual value of 0.3}
--------------------------------------------------------------
0.1=0.1000000000000000055511151231257827021181583404541015625
0.2=0.200000000000000011102230246251565404236316680908203125
0.3=0.299999999999999988897769753748434595763683319091796875
==============================================================
Calculation 0.1 + 0.2
______________________________________________________________
0.1=0.1000000000000000055511151231257827021181583404541015625
+0.2=0.200000000000000011102230246251565404236316680908203125
--------------------------------------------------------------
0.3=0.3000000000000000444089209850062616169452667236328125
==============================================================
Answer
--------------------------------------------------------------
0.3000000000000000444089209850062616169452667236328125
!=0.299999999999999988897769753748434595763683319091796875
---------------------------------------------------------------
第一段代码片段{答案0.2 + 0.2与实际值0.4相同}
---------------------------------------------------------------
Actual {Answer of 0.2+0.2 Is Same as actual value of 0.4}
---------------------------------------------------------------
0.2=0.200000000000000011102230246251565404236316680908203125
0.2=0.200000000000000011102230246251565404236316680908203125
0.4=0.40000000000000002220446049250313080847263336181640625
==============================================================
Calculation 0.2 + 0.2
---------------------------------------------------------------
0.2=0.200000000000000011102230246251565404236316680908203125
+0.2=0.200000000000000011102230246251565404236316680908203125
---------------------------------------------------------------
0.4=0.40000000000000002220446049250313080847263336181640625
==============================================================
Answer
--------------------------------------------------------------
0.4=0.40000000000000002220446049250313080847263336181640625
==0.4=0.40000000000000002220446049250313080847263336181640625
---------------------------------------------------------------