2016-10-14 6 views
1

내가 음수 값으로 작업 할 필요가그래서 내가 할 수있는 자바 스크립트

범위 사이의 임의의 숫자를 생성하는 기능을 설정하려고 마이너스를 포함하여 범위 사이의 임의의 숫자를 생성

randomBetweenRange(10, 20) 
randomBetweenRange(-10, 10) 
randomBetweenRange(-20, -10) 

이 내가 노력하고 무엇인가, 그것은 조금 .. 혼란과 randomBetweenRange(-20, -10)가 작동하지 않는 순간이다

function randomBetweenRange(a, b){ 
    var neg; 
    var pos; 

    if(a < 0){ 
     neg = Math.abs(a) + 1; 
     pos = (b * 2) - 1; 
    }else{ 
     neg = -Math.abs(a) + 1; 
     var pos = b; 
    } 

    var includeZero = true; 
    var result; 

    do result = Math.ceil(Math.random() * (pos + neg)) - neg; 
    while (includeZero === false && result === 0); 

    return result; 
} 

이 작업을 어떻게 만들 수 있습니까?

+1

중복 가능성을 빼기 받기/questions/1527803/generate-random-whole-number-in-a-specific-range –

답변

0
do result = Math.ceil(Math.random() * (pos + neg)) - neg; 

특히 Math.random() * (pos + neg)은 잘못된 범위를 반환합니다. pos = -20neg = -30 인 경우 pos와 neg 사이의 범위는 10이지만 조작은 -50을 반환합니다. 기술적으로 가능성의 양 (예 : {0,1}을 반환하는 함수를 생성하려는 경우 pos와 neg 사이의 범위는 1이지만 숫자에 두 가지 가능성이 있기 때문에 범위에 하나를 추가해야합니다. 당신이 Math.ceil를 사용하고 있기 때문에

귀하의 else 절은 또한 var pos

+1

명확하지 않은 경우 생성 될 수있는 가장 낮은 숫자가 0이고 가장 높은 숫자가 pos + neg. 그런 다음 결과에서 neg를 취하고 0/lower base가 이제 neg이고 가장 높은 (pos + neg)가 neg가됩니다. 아마도 나는 이해하기 어렵게 만들었을 것입니다. –

+0

-1 : 'Math.ceil'이 아닌 올바른 배포를 위해서는'Math.floor'를 사용해야합니다. – Bergi

1

은 처음에 작은 값이 항상 것입니다 가정 redeclares는 반환)과 결과에서 다른 일을 빼, 트릭을 할 것입니다이 코드는 참조 아래에 댓글을 남기고 주저하지 말고 물어보십시오!

var a=parseInt(prompt("First value")); 
 
var b=parseInt(prompt("Second value")); 
 
var result = 0; 
 

 
// Here, b - a will get the interval for any pos+neg value. 
 
result = Math.floor(Math.random() * (b - a)) + a; 
 
/* First case is we got two neg value 
 
\t * We make the little one pos to get the intervale 
 
\t * Due to this, we use - a to set the start 
 
*/ 
 
if(a < 0) { 
 
\t if(b < 0) { 
 
\t \t a = Math.abs(a); 
 
\t \t result = Math.floor(Math.random() * (a + b)) - a; 
 
\t } 
 
/* Second case is we got two neg value 
 
\t * We make the little one neg to get the intervale 
 
\t * Due to this, we use - a to set the start 
 
*/ 
 
} else { 
 
\t if(b > 0) { 
 
\t \t a = a*-1; 
 
\t \t result = Math.floor(Math.random() * (a + b)) - a; 
 
\t } 
 
} 
 
console.log("A : "+a+" | B : "+b+" | Int : "+(a+b)+"/"+Math.abs((a-b))); 
 
console.log(result);

0

당신은 시작 자체에 변수 'POS'를 선언했다. 그렇다면 왜 'else'부분에서 선언합니까? (var pos = b;)

따라서이 문장의 경우 결과가 Math.ceil (Math.random() * (pos + neg))입니다.

'pos'는 값을 가지지 않습니다.

0

는 -50과 50 사이의 숫자를 생성 할 경우 - 0에서 100 사이의 임의의 숫자는 다음 http://stackoverflow.com의 50

var randomNumber = Math.floor(Math.random() * 101) - 50; 
 

 
console.log(randomNumber);