Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

A-level Computing/AQA/Paper 1/Fundamentals of programming/Random number generation

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Built-in functions Subroutines (functions and procedures) An essential part of most games is the ability to use random numbers. These might be used to randomly place gold coins on a map, or to calculate whether you hit a target with a rifle at some distance. Dim rndGen As New Random() Dim randomNumber As Integer randomNumber = rndGen.Next() The above code will give you a random number between 1 and 2,147,483,647. You might well require a number that is a little smaller. To get a random number between two set numbers, in this case 5 and 10 you can use the following: randomNumber = rndGen.Next(5,10) So how exactly can we use this? Take a look at the following game: 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!") Adjust the code above to tell the user how many guesses they took to find the random number. HINT: you'll need a variable 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