随机不是随机的

时间:2013-06-11 13:55:02

标签: vb.net function random

Public Class Form1
Dim num1 As Integer = CInt(Int((10 * Rnd()) + 1))
Dim num2 As Integer = CInt(Int((10 * Rnd()) + 1))



End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    TextBox2.Text = num1 & "*" & num2
End Sub

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged

End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    If TextBox1.Text = num1 * num2 Then
        Label2.Text = "Correct!!11"
    Else
        Label2.Text = "Incorrect, sorry about that"
    End If
End Sub

结束班

当我运行此代码时,它只生成一个问题。这是6 * 8。如果我输入48,它可以工作。但如果我再次点击该按钮,它将不会产生另一个问题。它只会产生6 * 8。我需要它能够从1-10

生成随机乘法问题

2 个答案:

答案 0 :(得分:3)

当您初始化表单实例时,您只生成num1num2一次,因此每次单击该按钮时,它都只是重用相同的值。

每次单击按钮时都应生成新值:

Dim num1 As Integer
Dim num2 As Integer

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    num1 = CInt(Int((10 * Rnd()) + 1))
    num2 = CInt(Int((10 * Rnd()) + 1))
    TextBox2.Text = num1 & "*" & num2
End Sub

答案 1 :(得分:0)

如果你每次运行程序都得到6 * 8,包括完全停止和重新运行,那真的很奇怪,我不确定是什么。

但是,如果只是每次单击按钮时都会得到相同的问题,那么因为在声明变量时放入了Rnd()。如果你每次想要一个新的随机数,你将不得不在每次重新分配变量时放入某种循环。