当值为数十亿或更多时,VBA中的Mod溢出错误

问题描述 投票:2回答:2

我试图找到一个数字x的最大质数除数。当x小于10亿时,我的代码可以工作,但是当它大于10亿时,它会产生溢出错误并且调试会突出显示包含Mod的行。

 Sub Largest_Divisor()
    Dim x As Double
    Dim Q As Integer
    Q = 0
    Dim L() As Double
    x = 999999999#
    Dim i As Double
    For i = 775145 To 3 Step -2
        If x Mod i = 0 Then
            If IsPrime(i) Then
                ReDim Preserve L(Q) As Double
                L(Q) = i
                Q = Q + 1
            End If
        End If
    Next i
    MsgBox (Application.Max(L))
 End Sub
excel-vba modulo vba excel
2个回答
4
投票

我怀疑它是x大于约20亿,2,147,483,648准确,你有麻烦。

这是因为根据mod的文档,最多返回一个long,其值从-2,147,483,6482,147,483,647的值为32位有符号值。它没有在帮助文档中明确说明,但mod的论点也可能被强制用于long


0
投票

一个好的方法是使用这个功能:

Function Modulus(int1 As Double, int2 As Double) As Double

' This function will return int1 Mod int2. It is useful when |int1| exceeds 
' 2,147,483,647 as the VBA Mod function will then break.
'

Dim myInt As Integer

myInt = Int(int1 / int2)

Modulus = int1 - (myInt * int2)

End Function
© www.soinside.com 2019 - 2024. All rights reserved.