Vb.net 此代码是否因为需要很长时间而无法工作,或者是否已损坏?
我目前正在尝试生成随机数,直到一行中出现用户定义的相同数为止。数字从1到10不等 当我想要8个相同的数字排成一行时,需要3到5秒。它经历了大约500万个随机数。当我想要连续9次时,我已经离开了超过45分钟,没有任何运气 我认为它只需要大约10倍于8的时间,因为1/10的9次方比8次方大10倍 这是我的代码有问题还是我把数学搞砸了 我的代码:Vb.net 此代码是否因为需要很长时间而无法工作,或者是否已损坏?,vb.net,Vb.net,我目前正在尝试生成随机数,直到一行中出现用户定义的相同数为止。数字从1到10不等 当我想要8个相同的数字排成一行时,需要3到5秒。它经历了大约500万个随机数。当我想要连续9次时,我已经离开了超过45分钟,没有任何运气 我认为它只需要大约10倍于8的时间,因为1/10的9次方比8次方大10倍 这是我的代码有问题还是我把数学搞砸了 我的代码: Sub Main() Console.WriteLine("how many identical numbers in a row do you
Sub Main()
Console.WriteLine("how many identical numbers in a row do you want")
Dim many As Integer = Console.ReadLine
Dim storage(many - 1) As Integer
Dim complete As Boolean = False
Dim part As Integer = 0
Dim count As Integer = 0
Randomize()
While complete = False
count += 1
storage(part) = Int(Rnd() * 10) + 1
' Console.WriteLine(storage(part))
part += 1
If part = many Then
part = 0
End If
If storage.Min = storage.Max Then
complete = True
End If
End While
Console.WriteLine("===========")
Console.WriteLine(count.ToString("N"))
Console.WriteLine("===========")
For i = 0 To many - 1
Console.WriteLine(storage(i))
Next
Console.ReadLine()
End Sub
有不止一种可能性:可能是VB Rnd函数的编写使它永远无法工作,也可能是它有时确实需要很长时间。你需要做很多试验,并对它们进行平均,以确定你期望的1:10的比例是否如预期的那样有效 顺便说一句,你不需要保留最后十个数字。您只需记录下一个随机数与上一个随机数相等的次数。此外,我建议尝试另一种RNG(随机数生成器),例如.NET:
Module Module1
Dim rand As New Random()
Sub Main()
Console.Write("How many identical numbers in a row do you want: ")
Dim howMany As Integer = CInt(Console.ReadLine)
Dim count As Long = 0
Dim previous = -1
Dim soFar = 0
Dim n = 0
While soFar < howMany
count += 1
n = rand.Next(1, 11)
'Console.Write(n.ToString() & " ")
If n = previous Then
soFar += 1
Else
'If previous >= 0 Then
' Console.WriteLine(" X")
' Console.Write(n.ToString() & " ")
'End If
previous = n
soFar = 1
End If
End While
Console.WriteLine()
Console.WriteLine("Tries taken: " & count.ToString())
Console.ReadLine()
End Sub
End Module
模块1
Dim rand作为新的Random()
副标题()
Console.Write(“您希望一行中有多少相同的数字:”)
整数=CInt时的Dim数量(Console.ReadLine)
长度为0时的变暗计数
Dim PREVICE=-1
尺寸soFar=0
尺寸n=0
而现在有多少
计数+=1
n=下一个随机数(1,11)
'Console.Write(n.ToString()&')
如果n=上一个,则
soFar+=1
其他的
'如果上一个>=0,则
'控制台写入线(“X”)
'Console.Write(n.ToString()&')
"完"
以前的=n
soFar=1
如果结束
结束时
Console.WriteLine()
Console.WriteLine(“尝试次数:&count.ToString())
Console.ReadLine()
端接头
端模块
如果它是一个相同的数字生成器,为什么要使用任何形式的Rnd?将选项置于代码顶部的
上,然后阅读并使用,以了解网站的工作原理。感谢您的回复。我读了《如何提问》和《巡回演唱会》,对我得到的反对票数量感到困惑。这是因为我发布了所有的代码吗?我不能代表那些投反对票的人说话,但这篇文章相当模糊,标题非常糟糕(与其说是编程问题,不如说是代码审查(OT)请求)。