简体   繁体   中英

Random generator in Javascript with min and max value not working

I am new to JavaScript. I am trying to make an exercise program which generates a random number between a min and a max value. I am facing an issue in the program below. var2 + min is not working correctly. If I replace variable min with the actual value, then it works. What am I doing wrong?

var var1=Math.random()
var min = prompt("Enter Min value:")
var max = prompt("Enter max value:")
alert("min is "+min+" max is "+max)
var var2=var1*(max-min)
var var3=var2+min
var var4=Math.floor(var3)
alert("var1= "+var1+" var2= "+var2+" var3= "+var3+" Var4 "+var4)

Use:

var min = parseInt(prompt("Enter Min value:"), 10);
var max = parseInt(prompt("Enter max value:"), 10);

The problem is that these variables contain strings, so the expressions containing + are performing string concatenation rather than number addition.

And while you're learning, get in the habit of ending statements with ; . Javascript is lax about requiring this, but you should be explicit about it -- the rules for when semicolon can be omitted are a bit arcane.

var1 , var2 , var3 , etc. are not good variable names. Don't use them.

Your code isn't working because prompt returns a string. 1 - "2" is -1 , but 1 + "2" is "12" , as the addition operator is used for string concatenation.

Parse the strings into integers:

var min = parseInt(prompt("Enter Min value:"), 10);

prompt returns a string so you need to convert min and max to a number :

var min = Number(prompt("Enter Min value:"));
var max = Number(prompt("Enter max value:"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM