Random Number Generator
I'm not to famililar with Math.floor nor Math.random but i do know what they both do. So when I try to enter my first prompt and my second prompt it just comes at as 0 https://code.sololearn.com/WKhsmHXzvVB7/?ref=app
3/11/2022 1:01:38 AM
Your Mom
47 Answers
New Answerconvert number to string by concatenating the number to an empty string. it's a pair of double quotes "", but you can also use a pair of single quotes ''. you can use toString() too, but I'm lazy... using string templates seems to be faster, though... https://dev.to/sanchithasr/5-ways-to-convert-number-to-string-3fhd https://i.stack.imgur.com/mPxVd.png
To generate random numbers within a range use a function that takes two arguments(max, min) and return Math.random(max-min) + min
Your Mom function convert() { let min = ~~document.getElementById("num1").value; let max = ~~document.getElementById("num2").value; min = Math.ceil(min); max = Math.floor(max); document.getElementById("demo").innerHTML = Math.floor(Math.random() * (max - min + 1)) + min + ""; } converting to number(using ~~) and converting to string(using +"") seems to make the button click more responsive, too.
~~ is a risky shortcut to convert to number. Probably better to use Number(....), but Number returns a Nan for invalid inputs while ~~ converts it to 0. Javascript will convert values into strings when doing string concatenation, so + '' (an empty string) will convert the number to string. Might be a good idea to use type="number" for the inputs to prevent invalid string inputs. https://stackoverflow.com/questions/4055633/what-does-double-tilde-do-in-javascript
Sajjad Cheraghi with out the +1 in (max-min) the max is not inclusive. Remember math.random always produces a number less than 1 not one inclusive.
Math.random always returns a number less than 1 you have to make an adjustment to the random math.floor(math.round() * ((max - min + 1) + min)
So i use math.round? Im pretty sure math.floor rounds it too i think. I looked it up on w3schos
Yes you will still use math.floor as well so you can round the decimal that math.round creates. You will then * by the range you want. math.floor(math.round() * 100) Is random 0 to 99.
Okay i chnaged it up a bit but its doibg something weird now https://code.sololearn.com/WKhsmHXzvVB7/?ref=app
Look at your math.round() It needs to be: math.round() * ((max - min + 1) + min) You have: math.random() * max, min
Okay, it should have worked now but still in the begatives https://code.sololearn.com/WKhsmHXzvVB7/?ref=app
Let's build it: math.floor() math.floor(math.round()) math.floor(math.round() * ()) math.floor(math.round() * (())) math.floor(math.round() * ((max - min + 1) + min))