尝试使用visual basic为学校项目制作一个随机数生成器。用户将在textbox1和textbox 2中输入2个不同的值,按下按钮,这两个数字之间将生成一个随机数(此随机数将显示在textbox3中)。这对于项目来说太基础了,所以我决定添加2个复选框,当选中时会使生成的数字变为偶数或奇数。
真的需要一些算法来帮助将随机数限制为偶数或奇数。任何帮助是极大的赞赏! :)(checkbox1用于使其均匀,checkbox2用于奇数)
Dim answer As Integer
Dim result As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox3.Clear()
TextBox3.Text = answer
If CheckBox1.Checked = False And CheckBox2.Checked = False Then
answer = CInt(Int((TextBox2.Text * Rnd() + TextBox1.Text)))
End If
^上面的代码似乎也按照特定的顺序生成随机数,总是从0开始,对此的任何帮助将不胜感激:)
If CheckBox1.Checked = True Then
Do Until result = 0
result = CDec(TextBox1.Text / 2) - CInt(TextBox1.Text / 2)
Loop
If result = 0 Then
answer = CInt(Int((TextBox2.Text * Rnd() + TextBox1.Text)))
End If
End If
End Sub
答案 0 :(得分:0)
这就是我要解决这个问题的方法:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) 'Handles Button1.Click
'Parse the two numbers
Dim minValue = Integer.Parse(TextBox1.Text)
Dim maxValue = Integer.Parse(TextBox2.Text)
'Create a list of all possible valid numbers
Dim values = Enumerable.Range(minValue, maxValue - minValue).ToArray()
'Keep only the even numbers if selected
If CheckBox1.Checked Then
values = values.Where(Function (v) v Mod 2 = 0).ToArray()
End If
'Keep only the odd numbers if selected
If CheckBox2.Checked Then
values = values.Where(Function (v) v Mod 2 = 1).ToArray()
End If
'Check there are numbers
If values.Length = 0 Then
TextBox3.Text = "There no available numbers to choose."
Else
'`rnd` here is `System.Random` as I didn't know what `Rnd()` was.
TextBox3.Text = values(rnd.Next(0, values.Length)).ToString()
End If
End Sub
答案 1 :(得分:0)
您可以使用函数生成偶数或奇数,具体取决于选中的复选框,函数将使用mod来确定生成的数字是偶数/奇数。如果它不是您所需要的,那么它将再次尝试,直到生成的数字匹配。例如:
Private Sub btnGenerate_Click(sender As System.Object, e As System.EventArgs) Handles btnGenerate.Click
If chkOdd.Checked Then
GenerateOdd()
ElseIf chkEven.Checked Then
GenerateEven()
End If
End Sub
Private Function GenerateOdd()
Dim r = CInt(Math.Ceiling(Rnd() * 100))
If ((r Mod 2) = 0) Then
'r is even, generate another number and try again
GenerateOdd()
Else
'r is odd we have a match
yourTextBox.Text = r
Return r
End If
Return Nothing
End Function
Private Function GenerateEven()
Dim r = CInt(Math.Ceiling(Rnd() * 100))
If ((r Mod 2) = 0) Then
'r is even, we have a match
yourTextBox.Text = r
Return r
Else
'r is odd, generate another number and try again
GenerateEven()
End If
Return Nothing
End Function
我还没有尝试过,但你明白了!
*编辑 - (Rnd()* 100))是1到100之间的随机数