How to fix that math.random doenst show the wrong numbers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to fix that math.random doenst show the wrong numbers

https://code.sololearn.com/WWon16HAA6q5 Im trying to make a random code generator, But the var y = Math.floor(Math.random() * a + x); Doenst always show the right numbers, like when i input 1 - 10 then it shows 0 sometimes.. Can someone help me try to fix this? Thanks alot already :D

15th Jun 2019, 11:58 AM
mine
mine - avatar
8 Answers
+ 2
function check(){ var x = parseInt(document.getElementById("firstNumber").value); var a = parseInt(document.getElementById("secondNumber").value) - x; var y = Math.floor(Math.random() * a + x); //console.log("x: " + x + ", a: " + a + ", y: " + y) var demo = document.getElementById("output"); demo.innerHTML = "Your Number Is " + y; } one logic error and another error: you didn't convert the input given to integer so you made the calculation with Strings ... hope this helped! Happy Coding! 😄
15th Jun 2019, 12:08 PM
Anton Böhler
Anton Böhler - avatar
+ 3
@anton bohler Thank you alot!! Could you explain a bit of how it works what you did? Cause i dont really understand it.
15th Jun 2019, 12:17 PM
mine
mine - avatar
+ 3
Thank you @anton and @airee :D
15th Jun 2019, 12:28 PM
mine
mine - avatar
+ 2
It's because you didn't get the inputs as numbers, but as strings, so it doesn't add the number, just multiplies it. Also, your code is incorrect, because if you input for minimum 4, and for maximum 6, then it will generate a number between 4 and 9. If you want it to be correct, you should do it like this: function random(min, max) { return Math.floor(Math.random() * (max - min) + min); }
15th Jun 2019, 12:03 PM
Airree
Airree - avatar
+ 2
Airree the input where still String ...
15th Jun 2019, 12:10 PM
Anton Böhler
Anton Böhler - avatar
+ 2
Well, How can i do that with inputs? ( i made the variables of a and x a input field. So you can choose between wich numbers you want. )
15th Jun 2019, 12:12 PM
mine
mine - avatar
15th Jun 2019, 12:24 PM
Airree
Airree - avatar
+ 2
sure the only things I changes were here: var x = parseInt(document.getElementById("firstNumber").value); var a = parseInt(document.getElementById("secondNumber").value) - x; the function parseInt() takes as an input a string or int or even float and converts it to an int. Since the inputfields value is an string and not an int you need to convert it to int so that you can do math the way your used to do it. the second thing I did was to subtract x from a. This is done so that the random numbers only range from the smallest to the largest.
15th Jun 2019, 12:25 PM
Anton Böhler
Anton Böhler - avatar