随机数 js 最小值最大值 [英] random number js min max
问题描述
我正在尝试从 JavaScript 输入中获取 2 个数字之间的随机数.当我输入数字而不是 max.value 和 min.value 时,它可以工作,但不能使用变量.我不明白 js 中的 random 是如何工作的,在其他编程语言中我知道它很容易完成,比如 random(min,max) 所以我完全不明白为什么在 JS 中它这么难.谢谢.
I'm trying to get random number between 2 numbers from input in JavaScript. When I put numbers instead of max.value and min.value it works, but not with variable. I can't understand how does random in js work, in other programming languages I know it's easy done like random(min,max) so I totally don't understand why is it so hard in JS. Thank you.
function genRanNumb() {
document.getElementById('demo').innerHTML=Math.floor(Math.random()*(max.value-min.value+1)+min.value);
}
<input type="text" id="min">
<input type="text" id="max">
<button id="btn" onclick="genRanNumb()">button</button>
<p id="demo"></p>
推荐答案
我认为问题在于你的输入是 text 并且你随机想要 int 值解决方案是在 javascript 中用 parseFloat(yourvariable)
包围你的变量.
在您的情况下,您有:
I think the matter is your inputs are text and your random wants int values
The solution is to surrond your variable with parseFloat(yourvariable)
in javascript.
in your case you have :
function genRanNumb() {
document.getElementById('demo').innerHTML=Math.floor(Math.random()*(parseFloat(max.value)-parseFloat(min.value)+1)+parseFloat(min.value));
}
希望它能回答您的问题.
Hope it answer to your question.
为了更好的可读性和最好的兼容性,你应该这样写:
For better readability and best compatibility, you should write it like this:
function genRanNumb() {
var max = parseFloat(document.getElementById("max").value,10),
min = parseFloat(document.getElementById("min").value,10);
document.getElementById('demo').innerHTML=Math.floor(Math.random()*(max-min+1)+min);
}
这篇关于随机数 js 最小值最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!