How can I get random numbers from this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

How can I get random numbers from this code?

This script is suppose to create a random number but it returns the same number everytime it is ran. var roll = 0; var dice = Math.floor(Math.random() * 10) + 1; loop: do { roll = prompt("Guess the magic number!"); if (roll == dice) { alert("You win! " + dice + " is the magic number."); }else if (roll === '' || isNaN(roll)) { alert ("Please enter a number"); }else if (roll === null) { alert ("Cancelling Game...Goodbye!") ; break; } else { alert("You lose! " + dice + " is the magic number."); } }while (roll !== 1);

5th Apr 2017, 2:00 AM
LeRoy Summers
LeRoy Summers - avatar
2 Answers
+ 12
This: var dice = Math.floor(Math.random() * 10) + 1; should be placed inside the loop. Tested the fix on Code Playground and is working fine.
5th Apr 2017, 2:06 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
yea explanation: you initialized dice to a random number, but in the loop you never changed it, so it was always the same number
5th Apr 2017, 2:07 AM
Edward