Home > Blockchain >  Generating a random number from user Input
Generating a random number from user Input

Time:03-26

I've been trying to make a code that prompts the user to enter a minimum value and a maximum value in order to return a random value from the interval of those two. It's been hours now, and I can't really understand what I'm doing wrong. Also forgive me, I'm a student, so I'm still trying to understand these basic stuff.

I've tried running code, but it returns "NaN". I think the problem here is about the variables or something, so can someone try and point it out?

function userInput(low,high){
         return prompt("Enter a minimum value:");
         return prompt("Enter a maximum value:");
    }
    function generateNum(){
    return Math.floor(Math.random()*max-min 1) min;
    }
    function outputNum(q){
        document.getElementById("text1").innerHTML = q;
    }
    outputNum("Randomly generated number: " generateNum());
    
    var min = parseInt(userInput());
    var max = parseInt(userInput());

CodePudding user response:

Here is a working snippet. I corrected a few points (missing parentheses, a second return in a function that can never be reached and several more).

function userInput(){
  return [prompt("Enter a minimum value:"),
          prompt("Enter a maximum value:")];
}
function generateNum([min,max]){
  return  min  Math.floor(Math.random()*(max-min 1));
}
document.getElementById("text1").innerHTML = "Randomly generated number: " generateNum(userInput());
<div id="text1"></div>

CodePudding user response:

Another approach

<!DOCTYPE html>
<html>
    <title> Random Between Min & Max </title>
<body>
<h2>Random Between Min & Max</h2>

<button onclick="randBetween()">Try it</button>

<p id="random"></p>

<script>
function randBetween() {
  let min = parseInt(prompt("Please enter minimum number"));
  let max = parseInt(prompt("Please enter maximum number"));
  if (min !=null && max != null && min < max) {
  let randBetween = Math.floor(Math.random() * (max - min   1))   min;
  document.getElementById("random").innerHTML = randBetween;
  }else{
  alert("Enter min and max value and max value must be greater than min");
  }
}
</script>
</body>
</html>
  • Related