作业帮 > 数学 > 作业

vb随机产生10个两位数随机正整数,求其中素数之和(用过程实现判断一个数是否是素数)

来源:学生作业帮 编辑:百度作业网作业帮 分类:数学作业 时间:2024/05/16 03:57:33
vb随机产生10个两位数随机正整数,求其中素数之和(用过程实现判断一个数是否是素数)
Private Sub Command1_Click()
Dim a As Integer, r As Integer, s As Integer
s = 0
For a = 1 To 10
r = Int(90 * Rnd + 10)
Print r;
If f = True Then s = s + r
Next a
Print
Print "其中素数的总和="; s
End Sub
Public Function su(i As Integer, n As Integer) As Boolean
Dim f As Boolean
For i = 2 To n - 1
If n Mod i = 0 Then
f = False
Exit For
End If
Next i
If i < n - 1 Then
f = True
Print r;
End If
End Function
vb随机产生10个两位数随机正整数,求其中素数之和(用过程实现判断一个数是否是素数)
Public Function IsPrime(ByVal x As Integer) As Boolean
    Dim i As Integer
    IsPrime = True
    For i=2 To x-1
        If (x Mod i) = 0 Then
             IsPrime = False
            Exit Function
        End If
    Next
End Function

Private Sub Command1_Click()
    Dim a As Integer, r As Integer, s As Integer
    s = 0
    For a=1 To 10
        r = Int(90 * Rnd + 10)
        If IsPrime(r) Then s = s + r
   Next
   Print r
End Sub
再问: 为什么和一直是0啊?
再答: 那是随机数没有产生素数的缘故
把r = Int(90 * Rnd + 10) 改成
r = Int(90 * Rnd) + 10 试试
再问: 不行。。有素数的,但是和就是0,代码在题目补充那里
再答: Public Function IsPrime(ByVal x As Integer) As Boolean
    Dim i As Integer
    IsPrime = True
    For i=2 To x-1
        If (x Mod i) = 0 Then
             IsPrime = False
            Exit Function
        End If
    Next
End Function
 
Private Sub Command1_Click()
    Dim a As Integer, r As Integer, s As Integer
    s = 0
    For a=1 To 10
        r = Int(90 * Rnd) + 10  '<--修改这里,原来 r = Int(90 * Rnd + 10)
        If IsPrime(r) Then s = s + r
   Next
   Print s   '<--修改这里,原来误写为r
End Sub