我正在开发一个随机的PIN生成器程序,并在运行它时遇到一个神秘的错误。
Shared Function CreatePIN() As Integer
Dim PIN As String = ""
' Create the Random ID:
Dim possible As String = "0123456789"
For i As Integer = 0 To 9
PIN += possible.Chars(Math.Floor(Rnd() * possible.Length) Mod possible.Length)
Next
Return Convert.ToInt32(PIN)
End Function
我得到的错误是溢出!我正在创建的int要么太大要么太小而不能成为int。怎么会发生这种情况?这个程序没办法创建一个很大的int ...虽然显然它是。
答案 0 :(得分:2)
int最大值为2,147,483,647
您的代码可以生成9,999,999,999
使用long或更改代码以确保您不会生成超过2,147,483,647
离;
Function CreatePIN() As Long
Dim PIN As String = ""
' Create the Random ID:
Dim possible As String = "0123456789"
For i As Integer = 0 To 9
PIN += possible.Chars(CInt(Math.Floor(Rnd() * possible.Length) Mod possible.Length))
Next
Return Convert.ToInt64(PIN)
End Function
和一个脚注;始终打开option explicit ON
和option strict ON