VB 求数组里的素数
For k = 1 To 100
For i = 2 To a(k) - 1
If a(k) Mod i = 0 Then
num = num + 1
b(num) = a(k) '放入B数组
End If
Next i
Next k
一直提醒我下标越界什么回事??
前面的读数据有说啊a(k)有100个啊
Private Sub Command1_Click()
Dim k As Integer
Open App.Path & "\in5.dat" For Input As #1
For k = 1 To 100
Input #1, a(k)
Text1 = Text1 + Str(a(k)) + Space(2)
Next k
Close #1
End Sub 展开
Private Sub Command1_Click()
Dim i As Integer, num As Integer
Dim a(100) As Integer, b(100) As Integer, yes As Boolean
num = 0
Print "原来的数是:"
For k = 1 To 100
a(k) = Int(Rnd * 1000)
Print a(k);
yes = True
If k Mod 10 = 0 Then Print
For i = 2 To Sqr(a(k))
If a(k) Mod i = 0 Then yes = False: Exit For
Next i
If yes Then
num = num + 1
b(num) = a(k) '放入B数组 -------B数组也会下标越界的
End If
Next k
Print: Print "其中的素数是:"
For i = 1 To num
Print b(i);
If i Mod 10 = 0 Then Print
Next i
End Sub
前面的读数据有说a(k)有100个,这是怎么回事呢
有100个就照100个来判断啦
因为你定义的数组未声明大小的原因,比如下面声明大小后可正常运行。
若不确定数组大小可以用动态数组,先定义一个动态数组:dim a()
到使用的地方,再重定义上下限:
n=100
redim a(1 to n) ',当然,n 在重定义前就要确定
如果a中放了数据了,还要增加上限,还可以用 ReDim Preserve 语句来扩充数组:
a(15)=15
ReDim Preserve a(UBound(a) + 10) '只增加上限,不改变元素值
Private Sub Command1_Click()
Dim i As Integer
Dim a(100) '声明数组大小后可正常运行
Dim b(100)
For k = 1 To 100
For i = 2 To a(k) - 1
If a(k) Mod i = 0 Then
num = num + 1
b(num) = a(k) '放入B数组
End If
Next i
Next k
End Sub
前面的读数据有说a(k)有100个,这是怎么回事呢