一VB题,急需答案!!
20个两位随机正整数围成一圈,找出每四个相邻数之和中的最大值,并指出是哪四个相邻数。
追问:来自手机问问太谢谢了,不过有没有围成一圈呢?
20个两位随机正整数围成一圈,找出每四个相邻数之和中的最大值,并指出是哪四个相邻数。
追问:来自手机问问太谢谢了,不过有没有围成一圈呢?
答案:代码:
Private Sub Command1_Click()
Dim a(20) As Integer, i As Integer, j As Integer
Dim max As Integer, temp As Integer, flag As Integer
max = 0
Dim f1 As Integer, f2 As Integer, f3 As Integer, f4 As Integer '保存四个数的位置
Print "20个随即两位正整数是:"
Randomize
For i = 0 To 19
a(i) = Int(Rnd * 90) + 10
Print a(i);
Next i
For i = 0 To 19
temp = 0
For j = 0 To 3
temp = temp + a(((i + j) Mod 20))
Next j
If temp > max Then
max = temp
flag = i
f1 = flag + 1
f2 = flag + 2
f3 = flag + 3
f4 = flag + 4
If f1 > 20 Then f1 = f1 - 20
If f2 > 20 Then f2 = f2 - 20
If f3 > 20 Then f3 = f3 - 20
If f4 > 20 Then f4 = f4 - 20
End If
Next i
Print "每四个相邻数之和中的最大值是:", max
Print "这四个相邻的数是:"
Print "第" + Str(f1) + "个" + "第" + Str(f2) + "个" + "第" + Str(f3) + "个" + "第" + Str(f4) + "个"
End Sub
我运行了三次,都没问题,图:
'给你写个通用的吧
'单击窗体
Option Explicit
Const M = 20 '设为20个数
Const N = 4 '连续4个数
Private Sub Form_Click()
Dim i As Integer, j As Integer, arr(1 To M) As Integer, myarr(1 To M + N) As Integer
Dim max As Long, pos As Integer, sum As Long
Cls
For i = 1 To M '赋值
Randomize
arr(i) = Int(Rnd * 90 + 10)
myarr(i) = arr(i)
Next
For i = 1 To N
myarr(M + i) = arr(i)
Next
For i = 1 To M + N
For j = i To N
sum = sum + myarr(i)
Next
If max < sum Then
max = sum
pos = i
End If
sum = 0
Next
sum = 0
For i = 1 To M '输出20个数
Print i & ":";
Print arr(i);
sum = sum + 1
If sum Mod 5 = 0 Then Print
Next
For i = pos To pos + N - 1 '输出连续和最大数
If i > M Then
Print i - M & ":";
Print arr(i - M);
Else
Print i & ":";
Print arr(i);
End If
Next
Print "max=" & max
End Sub我可以教你噢,加我QQ,我在慢慢和你说
上一个:怎么用VB制作一个搜索程序
下一个:VB中接收键盘鼠标的方法