我为我的班级做了一个名为" Risk!"的作业,它的基础是你从1000点开始,并输入一个数字来冒险。你掷2个骰子。如果它是偶数,则会丢失并且输入将从分数中删除。如果它很奇怪,你就赢了,输入就会加到得分上。由于某种原因,分数没有正确显示。
Private Sub cmdQuit_Click()
Unload Me
End Sub
Private Sub cmdRollDice_Click()
intNumOutput1 = Int(Rnd * 6) + 1
intNumOutput2 = Int(Rnd * 6) + 1
lblNumOutput1.Caption = intNumOutput1
lblNumOutput2.Caption = intNumOutput2
intBothOutputs = intNumOutput1 + intNumOutput2
If intBothOutputs Mod 2 > 0 Then
intScore = intScore + intNumInput
MsgBox "odd, win"
Else
intScore = intScore - intNumInput
MsgBox "even, lose"
End If
lblTotal.Caption = "Your new point total is " & intScore
End Sub
Private Sub Form_Load()
Randomize
Dim intScore As Integer
Dim intNumOutput1 As Integer
Dim intNumOutput2 As Integer
Dim intBothOutputs As Integer
Dim intNumInput As Integer
txtNumInput.Text = intNumInput
intScore = 1000
txtNumInput.Text = ""
lblNumOutput1.Caption = ""
lblNumOutput2.Caption = ""
End Sub
答案 0 :(得分:2)
当您想在多个方法中使用变量(例如sub,function)时,您可以在任何方法之外声明变量。
现在,由于您在Form_Load
内声明了变量,因此无法在cmdRollDice_Click
或任何其他方法中使用它们。那么,当你在一个方法中使用它们时,会发生什么呢?好吧,如果您的代码上有Option Explicit
语句,则会出现运行时错误。如果不这样(这是你当前的情况),变量将被初始化 - 为零值 - 每次调用该方法时(注意:它们现在不是{{1}中声明的相同变量}} 的)。
因此,您需要在文件顶部(所有函数/子函数之前)声明变量,如下所示:
Form_Load
因此,作为一项规则:如果您不需要在该方法之外使用变量,则仅在方法内声明变量。
有关此内容的详细信息,请参阅Understanding the Scope of Variables
希望有所帮助:)
答案 1 :(得分:0)
请尝试以下。
Option Explicit
Private intScore As Integer
Private intNumOutput1 As Integer
Private intNumOutput2 As Integer
Private intBothOutputs As Integer
Private intNumInput As Integer
Private Sub cmdRollDice_Click()
Dim intNumOutput1 As Integer
Dim intNumOutput2 As Integer
Dim intBothOutputs As Integer
intNumOutput1 = Int(Rnd * 6) + 1
intNumOutput2 = Int(Rnd * 6) + 1
lblNumOutput1.Caption = intNumOutput1
lblNumOutput2.Caption = intNumOutput2
intBothOutputs = intNumOutput1 + intNumOutput2
If intBothOutputs Mod 2 > 0 Then
intScore = intScore + intNumInput
MsgBox "odd, win"
Else
intScore = intScore - intNumInput
MsgBox "even, lose"
End If
lblTotal.Caption = "Your new point total is " & CStr(intScore)
End Sub
Private Sub txtNumInput_Change()
If IsNumeric(txtNumInput.Text) Then
intNumInput = CInt(txtNumInput.Text)
End If
End Sub