vb 编程题、
1、求1-1000内的素数(过程要编写为函数)2、随机产生4位数,然后排序、将结果输出到一个文件。 大家帮个忙吧、小弟不大懂这个阿
1、求1-1000内的素数(过程要编写为函数)2、随机产生4位数,然后排序、将结果输出到一个文件。 大家帮个忙吧、小弟不大懂这个阿
答案:经常遇到类似的题目,可以参考此程序!VB 2008 调试通过!
Public Class Form1
Dim prime(100) As Integer
Dim CurrentIndex As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox1.ScrollBars = ScrollBars.Vertical
CurrentIndex = 1
prime(CurrentIndex) = 2
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim sum As Integer
For i = 3 To 200 Step 2 '显然,单数才有可能是素数
If IsPrime(i) Then
CurrentIndex = CurrentIndex + 1
prime(CurrentIndex) = i
End If
Next
sum = 0
For i = 1 To CurrentIndex '输出到 textbox 框中,一行一个数,并 累计 求和,结果也 输出 在 此框!
TextBox1.Text = TextBox1.Text & i & ", " & prime(i) & vbCrLf
sum = sum + prime(i)
Next
TextBox1.Text = TextBox1.Text & vbCrLf & "sum, " & sum & vbCrLf
End Sub
Private Function IsPrime(ByVal number As Integer) As Boolean '自定义函数,判断是否为素数
Dim i As Integer
IsPrime = True
For i = 1 To CurrentIndex
If number Mod prime(i) Then '用这个数除以自知 的 素数,能整除的显然不是 素数
Else
IsPrime = False
Exit Function
End If
Next
End Function
End Class