vb题 编一sub过程,对于已知正整数,判断该数是否是素数.然后调用该子过程,输出100至200之间的全部素数
我的程序是哪里错了?是调用不对吗?正确的是什么?Subss(nAsInteger)DimflagAsBoolean,iAsLongflag=TrueIfnMod2=0An...
我的程序是哪里错了?是调用不对吗?正确的是什么?
Sub ss(n As Integer)
Dim flag As Boolean, i As Long
flag = True
If n Mod 2 = 0 And n <> 0 Or n = 1 Then
flag = False
Else
For i = 3 To Sqr(n) Step 2
If n Mod i = 0 Then
flag = False: Exit For
End If
Next i
End If
ss = flag
End Sub
Private Sub Form_Click()
Dim k%
k = 0
For i = 100 To 200
Call ss(i%)
If ss Then
k = k + 1
End If
Next i
Print k
End Sub 展开
Sub ss(n As Integer)
Dim flag As Boolean, i As Long
flag = True
If n Mod 2 = 0 And n <> 0 Or n = 1 Then
flag = False
Else
For i = 3 To Sqr(n) Step 2
If n Mod i = 0 Then
flag = False: Exit For
End If
Next i
End If
ss = flag
End Sub
Private Sub Form_Click()
Dim k%
k = 0
For i = 100 To 200
Call ss(i%)
If ss Then
k = k + 1
End If
Next i
Print k
End Sub 展开
展开全部
sub函数是不能有返回值的,Function是可以有返回的。
我把代码修改了下,希望采纳!
' 这里sub改成 Function
Function ss(ByVal n As Integer)
Dim flag As Boolean, i As Long
flag = True
If n Mod 2 = 0 And n <> 0 Or n = 1 Then
flag = False
Else
' 这里改成 Math.Sqrt
For i = 3 To Math.Sqrt(n) Step 2
If n Mod i = 0 Then
flag = False : Exit For
End If
Next i
End If
ss = flag
End Function
Private Sub Form_Click()
Dim k%
k = 0
Dim i As Integer
For i = 100 To 200
' 这里改成 这样的
If ss(i) Then
k = k + 1
End If
Next i
Print(k)
End Sub
追问
用sub过程要怎么编
追答
如果你非要用sub过程的,sub过程是没有返回值的,你可以声明一个成员变量,来保存你的那个flag
' 在这里定义flag,删除原来的flag
Dim flag As Boolean
Sub ss(ByVal n As Integer)
Dim i As Long
flag = True
If n Mod 2 = 0 And n <> 0 Or n = 1 Then
flag = False
Else
' 这里改成 Math.Sqrt
For i = 3 To Math.Sqrt(n) Step 2
If n Mod i = 0 Then
flag = False : Exit For
End If
Next i
End If
End Sub
Private Sub Form_Click()
Dim k%
k = 0
Dim i As Integer
For i = 100 To 200
ss(i)
If flag Then
k = k + 1
End If
Next i
Print(k)
End Sub
这样写也是可以的
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询