3.综合应用
解析:素数的判断准则就是看是否该数除了1和其本身外别无其他约数即可。
文本框用text属性来显示计算结果;命令按钮的标题由caption属性来设置,单击命令按钮触发click事件;为了检测单选按钮是否选中,可以通过检测value属性来实现,当value为true时,表示单选按钮被选中,否则未被选中。
解题步骤:
第一步:建立界面并设置控件属性。
题目提供了程序用到的控件及其属性,见表1-4。
表 1-4
控 件 属 性 设 置 值
单选按钮 name caption op1 100-200之间素数
单选按钮 name caption op2 200-400之间素数
文本框 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
第三步:调试并运行程序。
第四步:按题目要求存盘。