只有整数和长类型才会出现溢出异常。为避免这种情况,您可以使用 System.Double 或 System.Numerics.BigInteger (或我认为的 BigDecimal)。
例如,如果您运行 3 个不同版本的阶乘:1 使用 long、1 使用 double 和 1 使用 biginteger,如下所示,值范围为 5 到 50 x 5:
'Long Factorial
Public Function FactorialInt64(ByVal n As Integer) As Int64
If n = 1 Then
Return 1
Else
Return n * FactorialInt64(n - 1)
End If
End Function
' Double Factorial
Public Function FactorialDouble(ByVal n As Integer) As Double
If n = 1 Then
Return 1
Else
Return n * FactorialDouble(n - 1)
End If
End Function
' BigInteger Factorial
Public Function FactorialBigInteger(ByVal n As Integer) As BigInteger
If n = 1 Then
Return 1
Else
Return n * FactorialBigInteger(n - 1)
End If
End Function
你会得到这样的结果:

您可以在我的博客文章中找到完整的源代码:VB.NET 中的阶乘和斐波那契