2

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());
1
  • ` return prompt("Enter a minimum value:"); return prompt("Enter a maximum value:");` the return exits the code. SO the second prompt would never fire Next you call min and max after you called generateNum Commented Mar 25, 2022 at 20:05

2 Answers 2

4

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

I simplified it further and added a .sort() to it. Als long as there are actual numbers entered into the prompt dialogues there will be min and max values. No need for an optional error message.

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.