顺序/有序随机数生成器

时间:2019-01-11 20:49:42

标签: vb.net visual-studio-2017

我需要它,因此所生成的下一个数字大于上一个...这是我的第一个面向对象编程的项目,所以我所知不多。另外,我如何使它在落入数字分组之前运行一定数量的模拟?这将不胜感激。

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(ByVal sender As Object, e As EventArgs) Handles Button1.Click
        Randomize()

        TextBox1.Text = Rand(1, 100)
        TextBox2.Text = Rand(1, 100)
        TextBox3.Text = Rand(1, 100)
        TextBox4.Text = Rand(1, 100)
        TextBox5.Text = Rand(1, 100)
        TextBox6.Text = Rand(1, 100)
        TextBox7.Text = Rand(1, 100)
        TextBox8.Text = Rand(1, 200)

    End Sub
    Public Function Rand(ByVal Low As Long, ByVal High As Long) As Long
        Rand = Int((High - Low + 1) * Rnd()) + Low
    End Function

End Class

2 个答案:

答案 0 :(得分:1)

在您的示例中没有涉及任何其他编码问题:

TextBox2.Text = Rand(Long.Parse(TextBox1.Text), 100)
TextBox3.Text = Rand(Long.Parse(TextBox2.Text), 100)
' ... etc.

100是基于您的代码的,除设置值外,您可能还具有一些用于设置下一个更高范围的算法。如果您的第一个随机数是100,那么其余的计算将是非随机的!

答案 1 :(得分:0)

创建要在表单级别填充的文本框的列表。

Private lstTextBoxes As List(Of TextBox)

填写Form.Load中的列表

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    lstTextBoxes = New List(Of TextBox) From {TextBox1, TextBox2, TextBox3}
End Sub

使用.net Random类。它比旧版本容易。

Private Rand As New Random

现在,您可以遍历文本框并填充“随机”数字。每次迭代的次数都将大于上一次,但在达到100时将停止。

 Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim highNumber As Integer
        For Each txtBox As TextBox In lstTextBoxes
            If highNumber >= 99 Then
                Return
            End If
            highNumber = Rand.Next(highNumber + 1, 100)
            txtBox.Text = highNumber.ToString
        Next
 End Sub