VB代码实现20-30次随机生成及TextBox值累加,排查Random异常
Hey there, let's work through your VB code problems one by one. I see two main issues here: the broken random number generation, and ensuring your loop runs 20-30 times with proper TextBox1 incrementing.
Why Your Random Values Aren't Working
The core problem is that you're creating a new Random instance inside your loop with a fixed seed (from TxtNumRnd.Text). When you initialize Random with the same seed, it will generate the exact same sequence of numbers every time. Even if the seed changes, creating a new instance in a tight loop can lead to duplicate values because the system clock doesn't tick fast enough between instantiations.
Fix: Initialize Random Once Outside the Loop
You should create your Random object once before starting the loop. This way, it uses a single seed (either your custom one or the default system clock seed) and generates a proper sequence of random numbers.
Corrected Full Code
Here's the revised code that addresses all your requirements:
' First, define your word array (assuming str1 is already set somewhere) Dim strWords As String() = str1.Split(",") ' Get the custom seed (optional; if empty, use default seed) Dim seedVal As Integer If Integer.TryParse(TxtNumRnd.Text, seedVal) = False Then seedVal = Environment.TickCount ' Fallback to system tick count if input is invalid End If ' Initialize Random ONCE outside the loop Dim rnd As New Random(seedVal) ' Generate loop count between 20 and 30 (inclusive) Dim loopCount As Integer = rnd.Next(20, 31) ' Next(min, max) is exclusive on max, so use 31 for 30 ' Reset TextBox1 if needed, or start from current value Dim currentCount As Integer = Val(TextBox1.Text) For i As Integer = 1 To loopCount ' Increment TextBox1 value currentCount += 1 TextBox1.Text = currentCount.ToString() ' Generate random number between 1 and 80 (your original requirement was 1-80) Dim randomNumber As Integer = rnd.Next(1, 81) ' Next(1,81) gives 1-80 inclusive ' Convert StrwrVal.Text to integer to avoid index errors Dim strIndex As Integer If Integer.TryParse(StrwrVal.Text, strIndex) AndAlso strIndex >= 0 AndAlso strIndex < strWords.Length Then ' Check if random number matches the target word's value If randomNumber = Val(strWords(strIndex)) Then Exit For ' Exit loop if match is found End If End If ' Append random number to TxtRnd1 TxtRnd1.Text = TxtRnd1.Text & vbNewLine & randomNumber Next
Key Improvements Explained
- Single Random Instance: By creating
rndoutside the loop, we ensure a proper sequence of non-repeating (or appropriately randomized) values. - Valid Loop Range:
rnd.Next(20,31)ensures the loop runs between 20 and 30 times (since the upper bound is exclusive). - Safe Type Conversion: Using
Integer.TryParseprevents crashes ifTxtNumRnd.TextorStrwrVal.Textcontains non-numeric values. - Cleaner Increment Logic: Storing
currentCountas an integer avoids repeated string-to-number conversions, which is more efficient and less error-prone. - Correct Random Number Range:
rnd.Next(1,81)generates numbers from 1 to 80 (your original comment mentioned "1-80的随机数(两位数)").
Quick Test for Randomness
If you want to verify the random generation works, run this simplified test:
Dim testRnd As New Random(5) ' Fixed seed for predictable test sequence For i As Integer = 1 To 5 Console.WriteLine(testRnd.Next(1,81)) Next
With seed 5, this should output a consistent sequence (like 45, 71, 14, 63, 29) — but if you move New Random(5) outside the loop, you'll get the full sequence instead of the same number every time.
内容的提问来源于stack exchange,提问作者Lutfi Maulana

