2011-09-15 4 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の間の2つのランダムな整数の合計、または任意の数を調べるためのコードです。1と6の間の2つの乱数の合計

以下は私自身の書面によるコードですが、これは問題ありません。私は2つのランダムな整数の和を達成している方法。 これは正しいですか ???再びあなたは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 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

私は唯一の*下のコードで生成された1個の*乱数を参照してください。 –

+3

あなたは乱数を2倍にして、2つの異なる乱数の合計を得ません。 –

答えて

2

)0と1の間の新たな乱数を生成するには、このようなものになるはずです。あなたは一度だけランダムに計算している

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

号とその値を2倍にします。 2つの異なる乱数を計算したいとします。

int random1 = a + (int) (Math.random() * (a-b)); 
int random2 = a + (int) (Math.random() * (a-b)); 
int sum = random1 + random2; 
関連する問題