【问题标题】:Randomizing While Loop Game VB随机循环游戏 VB
【发布时间】:2023-07-11 07:32:01
【问题描述】:

我正在用 VB 制作一个允许用户尝试猜数字的游戏。用户应该猜测数字,如果它们太高或太低,那么计算机会告诉他们。一旦用户做对了,计算机就会告诉他们做了多少次。我查看了这个网站和许多其他网站,以了解如何让我的 while 循环工作,但由于我有多个语句,这让我感到困惑。 目前,我无法让计算机告诉用户他们完成了多少次,以及他们何时尝试猜测数字,每次它说太高并永远循环,直到我结束程序。

这是程序,提前感谢您的帮助。

Sub Main()

    Dim usersguess, guesstime As Integer

    Randomize()

    Dim value As Integer = CInt(Int((20 * Rnd()) + 1))

    Console.WriteLine("You have to guess this number.")

    usersguess = Console.ReadLine()

    While usersguess < value Then
        Console.WriteLine("You are wrong. You're to low. Go higher ")
    End While
    While usersguess > value
        Console.WriteLine("Your too high. Go Lower.")
    End While

    While usersguess = value
        Console.WriteLine("Your correct. Well Done")
    End While

    Console.WriteLine("You took,{0}", guesstime)


End Sub

【问题讨论】:

  • VB.Net 中真的有While-Then 语句吗? o-o

标签: vb.net loops while-loop


【解决方案1】:

首先,您只要求用户输入一次 - ReadLine 也需要在一个循环中以要求多次猜测。使用该单个循环,您可以使用If 语句来检查答案:

usersguess = Console.ReadLine()
'keep looping until they get the right value
While userguess <> value
    'now check how it compares to the random value
    If usersguess < value Then
        Console.WriteLine("You are wrong. You're too low. Go higher ")
    ElseIf usersguess > value Then
        Console.WriteLine("You're too high. Go Lower.")
    End If

    'read another guess
    usersguess = Console.ReadLine()
End While

Console.WriteLine("You're correct. Well Done")

我还建议打开 Option StrictOption Explicit 以帮助清除可能出现的任何错误,在这种情况下,这意味着您需要将读取的文本显式转换为整数:

usersguess = Convert.ToInt32(Console.ReadLine())

请注意,如果您不输入数字,这本身就会失败...我将把如何正确处理这个问题作为练习,但会指向Int32.TryParse

【讨论】:

  • 谢谢你,但我还需要告诉用户他们花了多少次才得出正确答案,这是我坚持的主要部分
【解决方案2】:

您只需要一个计数器即可。

    Sub Main()
     Dim intAssignedcounter As Int32 = 0
    Dim usersguess

    Randomize()

    Dim value As Integer = 8 'CInt(Int((20 * Rnd()) + 1))

    Console.WriteLine("You have to guess this number.")

    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
            intAssignedcounter += 1
            Console.WriteLine("You are wrong. You're too low. Go higher ")
        ElseIf usersguess > value Then
            Console.WriteLine("You're too high. Go Lower.")
        End If

        'read another guess
        usersguess = Console.ReadLine()


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


    Console.ReadLine()

【讨论】:

  • 我也猜不到这太有用了