2011-09-15 2 views
1
public class SumOfTwoDice { 
    public static void main(String[] args) { 
     int SIDES = 6; 
     int a = 1 + (int) (Math.random() * SIDES); 
     int b = 1 + (int) (Math.random() * SIDES); 
     int sum = a + b; 
     System.out.println(sum); 
    } 
} 

여기에 1과 6 또는 임의의 주어진 숫자 사이의 두 개의 임의의 정수 합계를 확인하는 위의 코드가 있습니다.1과 6 사이의 2 개의 임의의 정수 합계

다음은 본인이 작성한 코드입니다. 괜찮습니까. 방법은 내가 두 개의 임의의 정수의 합계를 달성 오전. 이것이 맞습니까 ???

public class TestSample { 
    public static void main(String[] args) { 

     int a = Integer.parseInt(args[0]); // 1 
     int b = Integer.parseInt(args[1]); // 6 
     double ran = Math.random(); 
     System.out.println("Random Number" + ran); 
     double random; 

     if(a < b) 
      random = (b-a)*ran + a; 
     else 
      random = (a-b)*ran + b; 

     double sum = random + random; 
     System.out.println("Random Number" +(int)sum); 
    } 
} 
+4

I에서만 볼 * 난수 코드 하부에서 생성되는 하나 *. –

+3

두 개의 별개의 randoms의 합을 얻지 않고 난수를 두 배로 늘리고 있습니다. –

답변

2

당신은 이런 일이어야한다 0과 1 사이에 새로운 난수를 생성하기 위해 다시) 인 Math.random (사용해야합니다 : 당신은 단 한 번 무작위로 계산된다

public class TestSample { 
     public static void main(String[] args) { 

     int a = Integer.parseInt(args[0]); // 1 
     int b = Integer.parseInt(args[1]); // 6 
     double random1, random2; 

     if(a < b) { 
      random1 = (b-a)*Math.random() + a; 
      random2 = (b-a)*Math.random() + a; 
     } 
     else { 
      random1 = (a-b)*Math.random() + b; 
      random2 = (a-b)*Math.random() + b; 
     } 
     double sum = random1 + random2; 
     System.out.println("Random Number" +(int)sum); 
    } 
} 
1

번호 및 값을 두 배로 늘립니다. 두 개의 별개의 난수를 계산하려고합니다. 필수 XKCD

int random1 = a + (int) (Math.random() * (a-b)); 
int random2 = a + (int) (Math.random() * (a-b)); 
int sum = random1 + random2; 
관련 문제