我正在创建一个程序,该程序在两个单独的标签上显示两个随机数,然后我必须添加/减去它们,并且应该在文本框中输入答案
如何添加或减去数字并在文本框中输入答案?
我在 Visual Basic Windows 窗体应用程序中创建它
I think you are trying to do some security technique. what ever it may i appreciate your try. based on the question and what am understand, i will give the following code as suggestion for you.
Code to generate random numbers and random operators in label
Dim op As Integer ' to represent the operator
Private Sub Generate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Generate.Click
Dim Rand As New System.Random
op = Rand.Next(0, 3)'randomly select operator
lblfirst.Text = Rand.Next(0, 10)'first random number
lblsecond.Text = Rand.Next(0, 10)'second random number
If op = 0 Then ' choosing operator based on op
lblop.Text = "+"
ElseIf op = 1 Then
lblop.Text = "-"
ElseIf op = 2 Then
lblop.Text = "*"
End If
End Sub
Following is the check button's click event that will evaluate the expression in label and check with the answer in the text box: display the message as result
Private Sub check_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles check.Click
Dim result As Double = 0.0
If op = 0 Then
result = CDbl(lblfirst.Text) + CDbl(lblsecond.Text)
ElseIf op = 1 Then
result = CDbl(lblfirst.Text) - CDbl(lblsecond.Text)
ElseIf op = 2 Then
result = CDbl(lblfirst.Text) * CDbl(lblsecond.Text)
End If
If result = CDbl(TextBox1.Text) Then
MsgBox("Correct")
Else
MsgBox("Wrong")
End If
End Sub
这将在 0-10 之间添加两个随机数:
Dim Rand As New System.Random
Dim Rand1 as integer = Rand.Next(0, 10)
Dim Rand2 as integer = Rand.Next(0, 10)
YourLabel1.Text = Rand1.toString()
YourLabel2.Text = Rand2.toString()
YourAnswerLabel.Text = Rand1 + Rand2