简体   繁体   中英

JavaScript - random word generator

Am curious why is math.floor returns good results than math.ceil when I do random words generation and check in console.log .

Why can't math.ceil work perfectly? Is there something about incompatibility of math.ceil with math.random or is it how I assign and array number (item) of string elements?

Math.random() returns a number less than one (non-inclusive) but greater than 0 (inclusive)

Math.floor(Math.random() * 10); // returns a random integer from 0 to 9

Math.ceil(Math.random() * 10); // returns a random integer from 0 to 10 with a very low chance of 0

If Math.random results in 0 exactly, both Math.floor() and Math.ceil() will return 0 , but if Math.random() results in 0.00000001 , Math.floor() returns 0 and Math.ceil() returns 1 .

if you use Math.ceil(Math.random()*10) you lost first number and if you use Math.floor(Math.random()*10) you lost last Number but if you use Math.round(Math.random()*10) you can find 0 to 10 Number

 var k=2.1 console.log(Math.ceil(k)) console.log(Math.floor(k)) console.log(Math.round(k)) k=2.6 console.log(Math.ceil(k)) console.log(Math.floor(k)) console.log(Math.round(k))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM