[英]Random generator in Javascript with min and max value not working
I am new to JavaScript. 我是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. var2 + min
无法正常工作。 If I replace variable min with the actual value, then it works. 如果我将变量min替换为实际值,则它可以工作。 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.
Javascript对此要求不严格,但是您应该对此明确一点-何时可以省略分号的规则有点不可思议。
var1
, var2
, var3
, etc. are not good variable names. var1
, var2
, var3
等不是很好的变量名。 Don't use them. 不要使用它们。
Your code isn't working because prompt
returns a string. 您的代码无法正常工作,因为
prompt
返回了一个字符串。 1 - "2"
is -1
, but 1 + "2"
is "12"
, as the addition operator is used for string concatenation. 1 - "2"
为-1
,但1 + "2"
为"12"
,因为加法运算符用于字符串连接。
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
: prompt
返回一个string
因此您需要将min
和max
转换为number
:
var min = Number(prompt("Enter Min value:"));
var max = Number(prompt("Enter max value:"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.