Question: Generating a Random Number When generating a random number you should assign it to a variable so that it can be used later on in
Generating a Random Number
- When generating a random number you should assign it to a variable so that it can be used later on in the program. The general statement is
ranNum = Math.floor(Math.random()*highnum)+1
where highnum is replaced with the upper limit of the range of numbers desired.
- For example if you want random numbers between 1 and 50 you would write
ranNum = Math.floor(Math.random()*50)+1
- To print out the random number you would use a document.write statement, alert message, etc.
Generating a Certain Number of Random Numbers
- If you want to generate more than one random number, you can use a for loop. To generate 3 random numbers between 1 and 100 you would type
for (i=1; i<=3; i++) {
someNum = Math.floor(Math.random()*100)+1
document.write(someNum+" ")
}
Counting Within A Loop
- If you want to keep track of the sum of all of your numbers (i.e. if you want to calculate an average) you use a new variable within your loop. In this example, the variable total is used. Notice that its value has to be set to zero first.
var total = 0;
for (i=1; i<=3; i++) {
someNum = Math.floor(Math.random()*100)+1
document.write(someNum+" ")
total = total + someNum
}
alert(The total of all of your numbers is +total)
- Once your loop finishes, the variable total will be equal to the sum of all of your random numbers and its value will be given in an alert box.
Assignment #9
- Write a program where the click of a button will pop up an alert box which tells you the value of a random number between 1 and 100. Once you click on OK, all the numbers from 1 up to that random number are printed out on the page. Save the file as "9a_random.html" in your shared OneDrive folder.
- Write a program where the click of a button will pop up an alert box which tells you the value of a random number between 1 and 10. Once you click on OK, the sum of all the numbers from 1 up to that random number pops up in an alert box. Your alert messages should tell you what the numbers are. Save the file as "9b_random.html" in your shared OneDrive folder.
- Write a program where the click of a button will pop up an alert box which tells you the value of a random number between 1 and 10. Once you click on OK, the average of all the numbers from 1 up to that random number pops up in an alert box. Your alert messages should tell you what the numbers are.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
