3.綜合應用
解析:素數(shù)的判斷準則就是看是否該數(shù)除了1和其本身外別無其他約數(shù)即可。
文本框用Text屬性來顯示計算結果;命令按鈕的標題由Caption屬性來設置,單擊命令按鈕觸發(fā)Click事件;為了檢測單選按鈕是否選中,可以通過檢測Value屬性來實現(xiàn),當Value為True時,表示單選按鈕被選中,否則未被選中。
解題步驟:
第一步:建立界面并設置控件屬性。
題目提供了程序用到的控件及其屬性,見表1-4。
表 1-4
控 件 屬 性 設 置 值
單選按鈕 Name Caption Op1 100-200之間素數(shù)
單選按鈕 Name Caption Op2 200-400之間素數(shù)
文本框 Name Text1
命令按鈕 Name Caption Cmd1 計算
命令按鈕 Name Caption Cmd2 存盤
第二步:編寫程序代碼。
程序提供的代碼:
標準模塊代碼
Option Explicit
Sub putdata(t_FileName As String, T_Str As Variant)
Dim sFile As String
sFile = "\" & t_FileName
Open App.Path & sFile For Output As #1
Print #1, T_Str
Close #1
End Sub
Function isprime(t_I As Integer) As Boolean
Dim J As Integer
isprime = False
For J = 2 To t_I / 2
If t_I Mod J = 0 Then Exit For
Next J
If J > t_I / 2 Then isprime = True
End Function
窗體代碼
Private Sub Cmd1_Click()
Dim i As Integer
Dim temp As Long
'temp = ?
If Opt2.Value Then
For i = 200 To 400
' If isprime(?) Then
temp = temp + i
End If
Next
Else
For i = 100 To 200
If isprime(i) Then
temp = temp + i
End If
Next
End If
' Text1.? = temp
End Sub
Private Sub Cmd2_Click()
putdata "\out.txt", Text1.Text
End Sub
參考代碼:
Private Sub Cmd1_Click()
Dim i As Integer
Dim temp As Long
temp = 0
If Opt2.Value Then
For i = 200 To 400
If isprime(i) Then
temp = temp + i
End If
Next
Else
For i = 100 To 200
If isprime(i) Then
temp = temp + i
End If
Next
End If
Text1.Text = temp
End Sub
Private Sub Cmd2_Click()
putdata "\out.txt", Text1.Text
End Sub
第三步:調試并運行程序。
第四步:按題目要求存盤。