[英]Why is My Random Number in Javascript Code Concatenating Rather Than Adding?
I'm writing a basic random number generator (self teachingvia freeCodeCamp, going to use it for games with my 2 little boys). 我正在编写一个基本的随机数生成器(通过freeCodeCamp进行自我教学,将其用于与2个小男孩一起玩游戏)。 I'm using a basic HTML with no CSS added as the DOM and Javascript client side for the function (client side as my eldest is 5 and we have a family blog he loves to show people).
我正在使用没有添加CSS的基本HTML作为该功能的DOM和Javascript客户端(我的长辈是5,我们有一个他喜欢向人们展示的家族博客)。
The problem is that the code below is working to a point - the Math random function is fine, it works with Math.floor well and the multiplcation * (maximum - minimum +1) is all working as expected. 问题在于下面的代码在一定程度上起作用-Math随机函数很好,它在Math.floor上正常工作,并且乘法*(maximum-minimum +1)都按预期工作。
The issue is that the last segment is not working: + minimum. 问题是最后一个段不起作用:+最小值。 From the results I have looked at the formula is generating a result up to and including the multiplcation bracked, but then concatenating the minimum on the end, rather than adding it to the result.
从结果中,我看到公式可以生成一个结果,直到并包括乘以括号的结果,但是最后将最小值串联起来,而不是将其添加到结果中。
I have converted the maximum and minimum values to integers via parseInt when I first discovered the problem, in case there was an issue there (I didn't see why as they both worked fine in the multiplcation bracket), but that of course made no difference. 当我第一次发现问题时,我已经通过parseInt将最大值和最小值转换为整数,以防万一那里有一个问题(我不明白为什么它们在乘法运算中都可以正常工作),但是那当然没有区别。
function randomNumberFunction(maximum, minimum) { var numRan; var maximum = document.getElementById("maximum").value; var minimum = document.getElementById("minimum").value; parseInt(maximum); parseInt(minimum); numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum; alert(numRan); }
<div id="dice"> <form name="randomDice"> <h1>Get a random number</h1> <p>Maximum</p> <input id="maximum" type="number" name="random"><br> <p>Minimum</p> <input id="minimum" type="number" name="random"><br> <br> <button onclick="randomNumberFunction()">Get a random number</button> </form> </div>
I'm looking to be able to capture the minimum and maximum values a user inputs, and produce a random integer from that range. 我希望能够捕获用户输入的最小值和最大值,并从该范围生成一个随机整数。 Instead I get values like 01 when I input min 1, max 4, or 21. or 63 when inputting min 3, max 10.
相反,当我输入最小1,最大4或21时,会得到类似01的值;而当输入最小3,最大10时,则得到63的值。
You aren't assign value when you cast minimum and maximum variables 转换最小和最大变量时,您没有分配值
Try this: 尝试这个:
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
maximum = parseInt(maximum);
minimum = parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.