He estado tratando de crear un código que solicite al usuario que ingrese un valor mínimo y un valor máximo para devolver un valor aleatorio del intervalo de esos dos. Han pasado horas y realmente no puedo entender qué estoy haciendo mal. También perdóname, soy un estudiante, así que todavía estoy tratando de entender estas cosas básicas.
Intenté ejecutar el código, pero devuelve "NaN". Creo que el problema aquí es sobre las variables o algo así, ¿alguien puede intentar señalarlo?
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());Aquí hay un fragmento de trabajo. Corregí algunos puntos (paréntesis faltantes, un segundo retorno en una función que nunca se puede alcanzar y varios más).
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> Lo simplifiqué aún más y le agregué un .sort() . Siempre que haya números reales ingresados en los diálogos de solicitud, habrá valores mínimos y máximos. No es necesario un mensaje de error opcional.
Otro enfoque
<!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>