在VB6中测试两个Singles是否相等的最佳方法是什么?
我想测试两个Single值是否等于7个有效数字。
[This MSDN article建议使用类似
If Abs(a - b) <= Abs(a / 10 ^ 7) Then
valuesEqual = True
End If
但是,对于某些值,例如
Public Sub Main()
Dim a As Single
Dim b As Single
a = 0.50000005
b = 0.50000014
Debug.Print "a = " & a
Debug.Print "b = " & b
Debug.Print "a = b: " & (a = b)
Debug.Print "SinglesAreEqual(a, b): " & SinglesAreEqual(a, b)
// Output:
// a = 0.5000001
// b = 0.5000001
// b = b: False
// SinglesAreEqual(a, b): False
End Sub
Private Function SinglesAreEqual(a As Single, b As Single) As Boolean
If Abs(a - b) <= Abs(a / 10 ^ 7) Then
SinglesAreEqual = True
Else
SinglesAreEqual = False
End If
End Function
我发现获得所需结果的最简单方法是将值转换为字符串,但看起来非常丑陋:
Private Function SinglesAreEqual(a As Single, b As Single) As Boolean
SinglesAreEqual = (Str$(a) = Str$(b))
End Function
还有更好的方法吗?
我维护一个CAD / CAM应用程序,并且必须一直处理浮点数。我有一个称为fComp
的函数,当我需要测试相等性时会传递一个浮点值。 fComp
调用将舍入函数设置为一定精度。对于我们的系统,我四舍五入到小数点后六位。您可能需要更高或更低的价格,具体取决于应用程序。
fComp
函数存在,所以我有一个地方可以更改这些计算中使用的舍入因子。几年前,当我们开始制造更高精度的机器时,事实证明这很方便。
Public Function pRound(ByVal Value As Double, ByVal Power As Double) As Double
Dim TempValue As Double
Dim tSign As Double
TempValue = Value
tSign = TempValue
TempValue = Abs(TempValue)
TempValue = TempValue * 10 ^ (Power * -1)
TempValue = Fix(TempValue + 0.5)
TempValue = TempValue / 10 ^ (Power * -1)
pRound = TempValue * Sign(tSign)
End Function
要舍入到小数点后第六位
RoundedNumber = pRound(MyValue, -6)
负数在小数点右边,在正数左边。
相反,如果舍入并检验是否相等,则可以取两个数字的差,然后将其与一个因子进行比较
If Abs(a - b) < 0.000001 Then
您可以将0.000001
调整为所需的任何分辨率
我不相信您可以对大量有效数字使用single
数据类型。您将需要使用double
代替:
Dim a As Single
Dim s As String
s = "0.50000005"
a = 0.50000005
Debug.Print s & " " & a
以上输出:
0.50000005
0.5000001