The VBA function Rnd() generates a random number from 0 to 1. To generate a rand
ID: 3786769 • Letter: T
Question
The VBA function Rnd() generates a random number from 0 to 1. To generate a random number from 1-100, we can modify this function as follows: Number = 1 + Int(10*Rnd()) OR Dim Number as Integer Number = 1 + 100 * Rnd() An input box that asks the user to pick a number, 1-100, and compares the number to a randomly generated integer. The following scenarios should be accounted for: If the guess is greater than the randomly generated number, the user should be alerted that their guess was too high and prompted to guess again. If the guess is less than the randomly generated number, the user should be alerted that their guess was too low and prompted to guess again. For each guess, the program should output the trial number and the guessed value onto the spreadsheet. Once the correct guess has been made, the program should inform the user that they have won and output the number of guesses it took. The spreadsheet should include two buttons. One to run the program and one to clear the output.Explanation / Answer
Answer
Imports System
Public Class Guess
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim randomNum As Integer
Dim guessNum As Integer
Dim guessCount As Integer
Randomize 'Inittializes random-number generator
randomNum = Int((100 * Rnd) + 1) 'Generates a random number between 1 and 100
guessNum = 0
guessCount = 0
guessNum = InputBox("Guess a number bewteen 1 and 100.")
If guessNum = randomNum Then
guessCount = guessCount + 1
MsgBox ("Congrats! You guessed the number" & guessNum & ".")
MsgBox ("It took you " & guessCount & " to guess the number")
ElseIf guessNum > randomNum Then
guessCount = guessCount + 1
MsgBox ("Wrong Guess!! Too high. Try again.")
Else
guessCount = guessCount + 1
MsgBox ("Wrong Guess!! Too low. Try again.")
End If
End Sub
End Class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.