我在 VB.NET 中遇到了意外行为,这可能是一个错误,或者至少是类型和操作的处理方式不一致。下面的例子说明了这个问题:
Module Program
Sub Main(args As String())
Dim k1 As Int64 = 15368209579545345L ' odd number
Dim k2 As Int64 = 109L
Dim k3 As Int64 = k2 << 47
Dim k4 As Int64 = k1 - k2 * (2L ^ 47)
Console.WriteLine($"k1={k1}")
Console.WriteLine($"k2={k2}")
Console.WriteLine($"k3={k3}") ' Outputs: 15340386230730752
Console.WriteLine($"k4= k1 - k3 = {k4}") ' Outputs: 27823348814592, which is an even number
Console.WriteLine($"k4= k1 - k3 should be: {15368209579545345L - 15340386230730752L}")
Console.ReadLine()
End Sub
结束模块
这是发生的事情:
k1 是奇数。 k3 计算为 k2 << 47, which is a bitwise shift and works correctly. k4 is calculated using k1 - k2 * (2L ^ 47). The result should logically also be an odd number, as both k1 and k3 are aligned as expected. However, the result is an even number. The issue seems to lie in the expression (2L ^ 47). In VB.NET, the ^ operator is a power operator, not a bitwise XOR as in many other languages. This leads to unexpected type conversions and rounding errors during calculation.
为什么这在 C# 中不会发生? 在 C# 中,没有 ^ 幂运算符(它明确用于 XOR)。幂计算需要调用 Math.Pow 或类似方法,避免这种歧义。
还有其他人遇到过这个问题吗?这感觉像是 VB.NET 中的设计疏忽,因为这种不一致很容易导致微妙的错误。
VB 中的 XOR 运算符,
Dim k4 As Int64 = k1 - k2 * (2L Xor 47)