how to use math.random and math.floor | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

how to use math.random and math.floor

like it says in the title.

11th Jul 2016, 3:16 AM
PerfectlyColored
3 Answers
+ 6
Math.random() returns any number: - between 0 and 1 (0.43, 0.99, 0.45) - zero (0) - not including ONE (1) So Math.random() * 2 generates any number between 0 and 2, including 0 but not 2 (0.34, 1.78, 1.99) You can then wrap the generated random number inside Math.floor() to remove the decimals Math.floor(Math.random() * 2); Math.random() is evaluated first, say we got 1.99 Math.floor() is evaluated next, it will ignore the decimals and the result is 1 So if you do random() * 5 wrapped inside floor(), you're generating random whole numbers from 0 to 4 only
13th Jul 2016, 7:19 AM
gx021
gx021 - avatar
+ 1
/* Math.floor(x) returns the integer less than or equal to the input number */ var x = 2.3; console.log(Math.floor(x)); //prints 2 var x = Math.random(); // x can be any decimal between 0 and 1
11th Jul 2016, 8:45 AM
Sumanth Reddy
Sumanth Reddy - avatar
+ 1
/*Samuel, I like your example! i just modified that you wrote. Now code show the color name, not just numbers.*/ var variable = ["infrared waves","red", "orange","yellow","green","light blue","blue","violet","ultraviolet"]; var rnd = Math.floor (Math.random () * (variable.length)); switch (rnd){ case 0 : document.write("infrared"); break; case 1 : document.write("red"); break; case 2 : document.write("orange"); break; case 3 : document.write("yellow"); break; case 4 : document.write("green"); break; case 5 : document.write("light blue"); break; case 6 : document.write("blue"); break; case 7 : document.write("violet"); break; case 8 : document.write("ultraviolet"); break; }
26th Sep 2016, 8:36 PM
romalemonade
romalemonade - avatar