vb 猜数游戏 计算机随机生成一个1~100之间的整数(不显示),游戏者输入一个1~100之间的整数,计算机根据

题目:计算机随机生成一个1~100之间的整数(不显示),游戏者输入一个1~100之间的整数,计算机根据猜测结果给出太大、太小或猜中的提示。只允许用户猜5次,用for循环控制猜数次数。
请大神帮我改改看!

Dim x As Integer, y As Integer

Private Sub Command1_Click()
Randomize
x = Int(Rnd * 100) + 1
Text1.Visible = False
Text1.Text = x
End Sub

Private Sub Command2_Click()
y = Val(Text2.Text)
For i = 1 To 5
If x = y Then
Label3.Caption = "恭喜您猜对了!"
Text1.Visible = True
ElseIf x > y Then
Label3.Caption = "太小"
ElseIf x < y Then
Label3.Caption = "太大"
End If
If i = 5 Then
Exit Sub
End If
Next
End Sub

1、我仔细看了下,发现这段语句没什么用:
If i = 5 Then
Exit Sub
End If
因为i=5时,for循环也结束了,所以有没有这段循环都会结束。所以这段代码可以删除了,当然不删也不影响,考虑到代码的质量的话,删去吧。
2、我估计你是想在这里加入一段代码,让在猜对数字的情况下,结束循环吧?所以我这样改:
If x = y Then
Label3.Caption = "恭喜您猜对了!"
Text1.Visible = True
Exit Sub
温馨提示:内容为网友见解,仅供参考
第1个回答  2015-06-11
Dim x As Integer, y As Integer

Private Sub Command1_Click()
Randomize
x = Int(Rnd * 100) + 1
Text1.Visible = False
Text1.Text = x
End Sub

Private Sub Command2_Click()
Static i
i = i + 1
If i > 5 Then
MsgBox ("对不起,只能猜5次!")
Exit Sub
End If
y = Val(Text2.Text)
If x = y Then
Label3.Caption = "恭喜您猜对了!"
Text1.Visible = True
ElseIf x > y Then
Label3.Caption = "太小"
ElseIf x < y Then
Label3.Caption = "太大"
End If
End Sub追问

需要用for来控制循环次数

本回答被网友采纳
相似回答