여기 내 코드의 작은 숫자 나누기. 그것은 1 ~ 10 또는 50 ~ 100 등의 범위에 대해 잘 작동하지만 소수과 같이하려고하면난수 발생기는
randomNumber(0.01,0.05,5)
나는 0.27335과 1.04333 같은 나쁜 결과를 얻을 수 있습니다.
여기 내 코드의 작은 숫자 나누기. 그것은 1 ~ 10 또는 50 ~ 100 등의 범위에 대해 잘 작동하지만 소수과 같이하려고하면난수 발생기는
randomNumber(0.01,0.05,5)
나는 0.27335과 1.04333 같은 나쁜 결과를 얻을 수 있습니다.
계산에 +1하지 않았습니다. 없이 to-from
을해야합니다 +1 :
var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from +1) + from;
var result = Math.round(num * Math.pow(10, dec))/Math.pow(10, dec);
return result;
};
다음과 같이 코드는해야한다 :
사실var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from) + from;
var result = Math.round(num * Math.pow(10, dec))/Math.pow(10, dec);
return result;
};
, 그것은 더 다음과 같이 result
변수를 생략 단축 할 수 있습니다
var randomNumber = function (from, to, dec) {
var num = Math.random() * (to - from) + from; //Generate a random float
return Math.round(num * Math.pow(10, dec))/Math.pow(10, dec); //Round it to <dec> digits. Return.
};
Works! 고맙습니다. – mustacheMcGee
var randomNumber = function(from,to,dec)
{
var num = Math.random()*(to-from)+from;
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
왜 그냥 돌아 가지 않을까요? –
나는 var num = Math.random (from * from + 1) + from;이'var num = Math.random() * (to-from) + from; '이라고 생각한다. – Yoshi