+ 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
8 odpowiedzi
+ 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! 😄
+ 3
@anton bohler Thank you alot!! Could you explain a bit of how it works what you did? Cause i dont really understand it.
+ 3
Thank you @anton and @airee :D
+ 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);
}
+ 2
Airree the input where still String ...
+ 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. )
+ 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.