두 숫자 사이에 난수를 생성하는 난수 생성기를 만들려고합니다. 예를 들어, 나는 4의 임의의 수를 선택할 수 있도록하려는 것,의 내가 4와 10 사이의 임의의 숫자를 생성 할 가정 해 봅시다 - 여기에 10 것은 내가 뭘하려 :Javascript 무작위 정수 두 숫자 사이
var randNumMin = 4;
var randNumMax = 10;
var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
그러나, 작동하지 않았고 4 ~ 10 사이의 이상한 난수를 생성했으며 일부는 0으로 시작했습니다.이 작업을 수행하는 올바른 알고리즘은 무엇입니까?
$(function() {
$('#generateRandNums').click(function() {
var numCount = document.getElementById("randNumCount").value;
var randNumMin = document.getElementById("randNumMin").value;
var randNumMax = document.getElementById("randNumMax").value;
if (numCount.match(/^[\d]*$/) && randNumMin.match(/^[\d]*$/) && randNumMax.match(/^[\d]*$/)) {
if (numCount == "" || randNumMin == "" || randNumMax == "") {
alert ("Please fill out all forms then try again.");
} else {
if (randNumMin>randNumMax) {
alert ("Please make sure your first number is smaller than the second, then try again.");
} else {
if (randNumMin<0) {
alert ("Please make sure that you generate a positive number of random numbers, then try again.");
} else {
if (numCount>1) {
var randResult = ("You generated " + numCount + " random numbers between " + randNumMin + " and " + randNumMax + " and got the numbers ")
oneNumber = 0;
} else {
var randResult = ("You generated a random number between " + randNumMin + " and " + randNumMax + " and got the number ");
oneNumber = 1;
}
for (i=0;i<numCount;i++) {
//Get a random number between randNumMin and randNumMax
var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
if (i == numCount-1) {
if (oneNumber == 0) {
randResult = (randResult + "and " + randInt + ".");
} else {
randResult = (randResult + randInt + ".");
}
} else {
randResult = (randResult + randInt + ", ");
}
}
$("#randNumResults").val(randResult);
}
}
}
} else {
alert ("Make sure you only enter numbers and no spaces, then try again.");
}
});
});
나는이 함께 randInt 라인을 교체 시도 : : 그것은 여전히 작동하지 않았다
var randInt = Math.floor((Math.random() * ((randNumMax + 1) - randNumMin)) + randNumMin);
여기
내가있는 알고리즘을 구현하고있어 코드입니다. 알고리즘이 잘못되었거나 기능에 잘못 통합되어 있는지 확실하지 않습니다. 대답은 고맙습니다. 감사합니다.
나를 위해 잘 작동하는 것 같다위한 좋은 유틸리티를 가지고있다. – qw3n
잘 보인다 : http://jsfiddle.net/j08691/LYQKV/ – j08691
내가 그것을 구현하고있어 기능을 추가 할 것 [자바 스크립트에서 두 숫자 사이의 임의] **의 –