gpt4 book ai didi

VB.NET - 从随机数生成器中删除数字

转载 作者:行者123 更新时间:2023-12-02 08:57:42 26 4
gpt4 key购买 nike

我正在尝试创建一个彩票模拟器。彩票有 6 个号码,生成的号码必须在 1 - 49 之间,并且不能在下一个生成的号码中。我尝试过使用 OR 函数,但我不完全确定我是否正确使用它。任何帮助都会很棒。谢谢。

Public Class Form1

Private Sub cmdRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRun.Click
''#Creates a new Random class in VB.NET
Dim RandomClass As New Random()



''####################################
Dim RandomNumber1 As Integer
RandomNumber1 = RandomClass.Next(1, 49)
''#Displays first number generated
txtFirst.Text = (RandomNumber1)



''####################################
Dim RandomNumber2 As Integer
RandomNumber2 = RandomClass.Next(1, 49)
If RandomNumber2 = RandomNumber1 Then
RandomNumber2 = RandomClass.Next(1, 49)
End If

''#Displays second number generated
txtSecond.Text = (RandomNumber2)



''####################################
Dim RandomNumber3 As Integer
RandomNumber3 = RandomClass.Next(1, 49)
If RandomNumber3 = RandomNumber2 Or RandomNumber2 Then
RandomNumber3 = RandomClass.Next(1, 49)
End If

''#Displays third number generated
txtThird.Text = (RandomNumber3)



''####################################
Dim RandomNumber4 As Integer
RandomNumber4 = RandomClass.Next(1, 49)
If RandomNumber4 = RandomNumber3 Or RandomNumber2 Or RandomNumber1 Then
RandomNumber4 = RandomClass.Next(1, 49)
End If

''#Displays fourth number generated
txtFourth.Text = (RandomNumber4)



''####################################
Dim RandomNumber5 As Integer
RandomNumber5 = RandomClass.Next(1, 49)
If RandomNumber5 = RandomNumber4 Or RandomNumber3 Or RandomNumber2 Or RandomNumber1 Then
RandomNumber5 = RandomClass.Next(1, 49)
End If

''#Displays fifth number generated
txtFifth.Text = (RandomNumber5)



''####################################
Dim RandomNumber6 As Integer
RandomNumber6 = RandomClass.Next(1, 49)
If RandomNumber6 = RandomNumber5, RandomNumber4, RandomNumber3, RandomNumber2, RandomNumber1 Then
RandomNumber6 = RandomClass.Next(1, 49)
End If

''#Displays sixth number generated
txtSixth.Text = (RandomNumber6)


End Sub

最佳答案

不要使用“If”,而使用“While” - 换句话说,不断生成随机数,直到找到新的随机数。目前,如果您获得重复项,然后在第二次尝试时获得重复项,您将继续前进。

此外,虽然我不是 VB 专家,但我相信您需要完整地指定每个比较,因此不要这样:

If RandomNumber3 = RandomNumber2 Or RandomNumber2 Then
RandomNumber3 = RandomClass.Next(1, 49)
End If

你需要:

While RandomNumber3 = RandomNumber1 Or RandomNumber3 = RandomNumber2 Then
RandomNumber3 = RandomClass.Next(1, 49)
End While

这里有一些替代方案 - 例如生成数字 1-49,对它们进行洗牌,然后获取前 6 个结果...或者保持“选择直到出现新结果”,但将结果保留在一个集合中。无论哪种方式,您都可以避免大量的代码重复。

关于VB.NET - 从随机数生成器中删除数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2823910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com