Vb猜测游戏随机发生器损坏

时间:2015-10-14 16:03:20

标签: vb.net random

在我的代码中,我现在已经意识到我必须使用New Random函数,我的代码之前使用Randomize然后是数字,但现在它出现了大量错误,甚至不让我运行程序。我认为这只是一个小错误,但我只是需要一些帮助来获得最后一点 下面是代码并感谢您的帮助:)

我无法让代码与随机生成的数字一起使用,我必须使用New Random函数我不能使用randomize()有没有人知道如何帮助这里是代码。

    Dim timestook As Int32 = 1
    Dim usersguess As Integer
    Dim value = New Random(0 - 19)
    Console.WriteLine("You have to guess this number. It is between 1 and 20. Good Luck !")

    usersguess = Console.ReadLine()
    'keep looping until they get the right value
    While usersguess <> value
        'now check how it compares to the random value
        If usersguess < value Then
            timestook = timestook + 1
            Console.WriteLine("You're too low. Go higher ")
        ElseIf usersguess > value Then
            Console.WriteLine("You're too high. Go Lower.")
            timestook = timestook + 1
        End If
        'If they are wrong the code will run again,after telling the user if they are too high or too low.
        usersguess = Console.ReadLine()

    End While
    '        Console.WriteLine("You're correct. Well Done")
    If usersguess = value Then
        Console.WriteLine("You took,{0}", timestook)
    End If
    Console.ReadLine()
End Sub

2 个答案:

答案 0 :(得分:1)

您想要在how to use random numbers上进行一些Google搜索。您的问题是您没有创建Random对象来处理随机数生成。

以下是修改代码的方法:

Dim randNumGen As New Random() 'Create Random object
Dim value As Integer = randNumGen.Next(0, 20) 'set value equal to a new random number between 0-19

请注意,为了便于阅读和简化,可以进一步重构此代码(例如将timestook = timestook + 1更改为timestook += 1并选择更好的变量名称,例如numberOfGuesses而不是timestook,等

答案 1 :(得分:1)

表达式New Random(0-19)完全不符合您的想法,名称 NOT 返回一个整数。相反,它创建了一个Random对象的实例,这是一种知道如何创建新随机值的类型。表达式的0-19部分是Random object's constructor种子,与传递值-19相同。

这看起来像是家庭作业或个人练习,所以我觉得在这种情况下使用Random类型作为参考的单独示例比在我修复代码示例时更好。问题:

Dim rnd As New Random()
For i As Integer = 0 To 10
    Console.WriteLine(rnd.Next(0, 20))
Next i

此处还值得一提的是,您通常只需要一个 Random对象用于整个程序,或者至少只需要一个Random对象用于程序的每个逻辑部分。创建新的Random对象会重置种子,为了获得最佳结果,您希望在稍后对同一实例的后续调用中遵循相同的种子。

相关问题