VB.Net 一些添加后的双重比较

VB.Net Double comparison after some additions

在向双变量添加一些值后,我遇到了一个奇怪的情况。 当多次将 (0.2) 添加到双变量时会出现问题 - 我认为它只发生在 (0.2) - 例如:考虑这段代码:

Dim i As Double = 2
i = i + 0.2
MsgBox(i) '2.2
MsgBox(i > 2.2) 'False >> No problem

但是如果我多次添加 (0.2):

Dim i As Double = 2
i = i + 0.2
i = i + 0.2
MsgBox(i) '2.4
Msgbox(i > 2.4) 'True >> !!!!

还有

Dim i As Double = 2
For x As Integer = 1 to 5
    i = i + 0.2
Next
MsgBox(i) '3
Msgbox(i > 3) 'True >> !!!!

我用其他值尝试了相同的代码,我没有遇到这个问题:

Dim i As Double = 2
i = i + 0.5
i = i + 0.5
MsgBox(i) '3
Msgbox(i > 3) 'False >> No problem

有人对此有解释吗?? 谢谢

如果您采用示例 3,您会发现结果实际上是 3.0000000000000009

问题出在双精度数的舍入上。

如果您更改数据类型 decimal,问题就解决了:

Sub Main()

    Dim i As Decimal = 2

    For x As Integer = 1 To 5
        i = i + 0.2
    Next
    MsgBox(i) '3
    MsgBox(i > 3) 'False >> No problem

End Sub

This is 关于 C# 但是,我想,对于 vb.net.

也是一样的

此问题称为“Accuracy Problems (Wikipedia Link)

The fact that floating-point numbers cannot precisely represent all real numbers, and that floating-point operations can not precisely represent true arithmetic operations, leads to many surprising situations. This is related to the finite precision with which computers generally represent numbers.