跳转至内容

编程基础:随机数生成

来自维基教科书,开放书籍,开放世界

试卷 1 - ⇑ 编程基础 ⇑

← 内置函数 随机数生成 子程序(函数和过程) →


大多数游戏的一个重要部分是使用随机数的能力。这些可能用于随机放置地图上的金币,或者计算你是否在一定距离内用步枪击中目标。

Dim rndGen As New Random()
Dim randomNumber As Integer
randomNumber = rndGen.Next()

上面的代码将为您提供 1 到 2,147,483,647 之间的随机数。您可能需要一个稍微小一点的数字。要获得两个设置数字之间的随机数,在本例中为 5 和 10,您可以使用以下代码

randomNumber = rndGen.Next(5,10)

那么我们究竟如何使用它呢?看一下下面的游戏

Dim rndGen As New Random()
Dim randomNumber As Integer
Dim guess as Integer
randomNumber = rndGen.Next(1,100)
console.writeline("Please guess the random number between 1 and 100")
Do 
  console.write("your guess:")
  guess = console.readline()
  if guess > randomNumber
    console.writeline("Too High")
  end if
  if guess < randomNumber
    console.writeline("Too Low")
  end if
Loop While guess <> randomNumber
console.writeline("Well done, you took x guesses to find it!")

调整上面的代码以告知用户他们找到了随机数需要多少次猜测。提示:您需要一个变量

答案

    Sub Main()
        Dim rndGen As New Random()
        Dim randomNumber As Integer
        Dim guess As Integer
        Dim count As Integer = 1
        randomNumber = rndGen.Next(1, 100)


        Console.WriteLine("Please guess the random number between 1 and 100")
        Do
            Console.Write("your guess:")
            guess = Console.ReadLine()
            If guess > randomNumber Then
                Console.WriteLine("Too High")
            End If
            If guess < randomNumber Then
                Console.WriteLine("Too Low")
            End If
            If guess <> randomNumber Then
                count = count + 1
            End If
            If guess = randomNumber Then
                Console.WriteLine("Well done, you took " & count & " guesses to find it!")
            End If

        Loop
    End Sub
华夏公益教科书