我需要帮助在VB.NET中创建一个基本数组。
目标是将随机数加载到每个阵列位置,然后显示数组的内容。有100个索引值,从1到100。
这是我到目前为止所做的:
Dim Output As String
Dim RandomNumber As Integer
Dim n As Integer
Dim NumberArray(101) As Integer
NumberArray(n) = RandomNumber
For n = 1 To 100
Randomize()
RandomNumber = Int(Rnd() * 100) + 1
Next
Output = Output & "Index #" & n & vbTab & NumberArray(n) & vbCrLf
TextBox1.Text = Output
我收到的输出是:
索引#101 0
我无法弄清楚如何输出整个数组列表。
答案 0 :(得分:1)
你所有的循环都在生成随机数,并将它们分配给变量,然后在下一次迭代中被覆盖。您需要将数组赋值和输出字符串连接移动到循环内部。
Dim Output As String = ""
Dim RandomNumber As Integer
Dim n As Integer
Dim NumberArray(101) As Integer
For n = 1 To 100
Randomize()
RandomNumber = Int(Rnd() * 100) + 1
NumberArray(n) = RandomNumber
Output &= "Index #" & n.ToString & vbTab & NumberArray(n).ToString & vbCrLf
Next
TextBox1.Text = Output
请注意,上述代码并非理想。'为了清楚起见,我特意以这种方式编写了这样一来,以保留尽可能多的提问者的原始代码。
答案 1 :(得分:1)
我建议使用RANDOM 试试这个:
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Dim random As New Random(Now.Millisecond)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim array() As Integer = {}
For I As Integer = 1 To 100
ReDim Preserve array(I - 1)
array(I - 1) = random.Next(0, 101)
Next
MsgBox(arrToStr(array))
End Sub
Function arrToStr(arr As Integer()) As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 0 To UBound(arr)
If i = UBound(arr) Then
sb.Append(arr(i).ToString)
Else
sb.Append(arr(i).ToString & ", ")
End If
Next
Return sb.ToString
End Function
End Class
以你的风格:
Randomize()
Dim Output As String = String.Empty
Dim NumberArray(99) As Integer
For n As Integer = 0 To 99
Dim RandomNumber As Integer = CInt(Int(Rnd() * 100) + 1)
NumberArray(n) = RandomNumber
Output &= "Index #" & n.ToString & Space(4) & NumberArray(n) & vbCrLf
Next
TextBox1.Text = Output