即使我的所有数据类型都很好,我也遇到过这个错误。
运行时错误6溢出
这是功能:
Function equation(x As Long) As Long
Dim a As Long, b As Double
a = Int(((x - 2) Mod 8) / 6) + 2 * Int((x - 2) / 8)
b = (x + a - 1) / 2
equation = Abs(4 * b + 5 + 2 * Int(b))
End Function
当x = 572662307
溢出时遇到错误。
答案 0 :(得分:3)
x = 572662307
。是32位有符号整数(约20亿)的最大值的四分之一,因此您的算术运算可能确实会达到这个值。
在VBA中Long
是一个32位有符号整数,不像C#中那样是64位有符号整数。我建议将a
和x
更改为Double
。
您还可以展开您的功能,以便检查调试器中的所有中间步骤:
Function equation(x As Double) As Double
Dim a As Double, b As Double, c As Double, d As Double, e As Double, f As Double, g As Double
a = (x - 2) Mod 8
b = a / 6
b = Int( b )
c = (x - 2) / 8
d = 2 * Int( c )
e = b + d
f = (x + a - 1)
f = f / 2
g = 4 * b + 5 + 2 * Int( f )
equation = Abs( g )
End Function