VB:为什么不能打印出100以内的素数?结果有点像乱码。

来源:百度知道 编辑:UC知道 时间:2024/05/24 12:24:31
Private Sub Form_Click()
Dim Prime() As Integer, I As Integer
Dim M As Integer, J As Integer
For I = 2 To 100
If sushu(I) Then
M = M + 1
ReDim Preserve Prime(M)
Prime(M) = I
End If
For J = 1 To UBound(Prime)
Print Prime(J);
If J Mod 10 = 0 Then Print
Next J
Next I
End Sub

Private Function sushu(N As Integer) As Boolean
Dim I As Integer
sushu = False
For I = 2 To Sqr(N)
If N Mod I = 0 Then Exit Function
Next I
sushu = True
End Function

'我想每十个一行来显示100以内的所有素数。高手请看看这个程序错在哪里?

把你的程序改了一下,你是用数组来存放素数的,
For i=2 to 100这上循环是用来判断有哪些素数,并将其记录
而For J = 1 To UBound(Prime) 这个是用来输出找到的所有素数的
如果你用嵌套结构,每找一个数都将会输出一遍找到的所有的素数,当然会出错,只要将两个循环由嵌套结构变成顺序结构即可,如果一定要嵌套,你可以找到一个输出一个,不用数组,这样也不会重复而正确输出

这时,你还没有判断完,所以不能输出
Private Sub Form_Click()
Dim Prime() As Integer, I As Integer
Dim M As Integer, J As Integer
For I = 2 To 100
If sushu(I) Then
M = M + 1
ReDim Preserve Prime(M)
Prime(M) = I
End If
Next I
For J = 1 To UBound(Prime)
Print Prime(J);
If J Mod 10 = 0 Then Print
Next J
End Sub

Private Function sushu(N As Integer) As Boolean
Dim I As Integer
sushu = False
For I = 2 To Sqr(N)
If N Mod I = 0 Then Exit Function
Next I
sushu = True
End Function

Private Sub Form_Click()
Dim Prime() As Integer, I As Integer
Dim M As Integer, J As Integer