2014-11-23 22 views
5
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); 
    } 
} 

我已經從Sedgewick在他們的在線網站上的書「Java編程入門」中看到了這段代碼。兩個骰子的Java總和 - 這個代碼是否高於6?

我只是有一個問題,即是否ab,如果正巧Math.random()1.0也可能會被上述6?或者我錯了嗎?

1.0 * 6 + 1 = 7?

+1

'Math.random()'不會返回1.0 – 2014-11-23 08:07:22

回答

3

Math.random()不能返回1.0,所以ab不能7.

/** 
* Returns a <code>double</code> value with a positive sign, greater 
* than or equal to <code>0.0</code> and less than <code>1.0</code>. <----------- 
* Returned values are chosen pseudorandomly with (approximately) 
* uniform distribution from that range. 
* 
* <p>When this method is first called, it creates a single new 
* pseudorandom-number generator, exactly as if by the expression 
* <blockquote><pre>new java.util.Random</pre></blockquote> This 
* new pseudorandom-number generator is used thereafter for all 
* calls to this method and is used nowhere else. 
* 
* <p>This method is properly synchronized to allow correct use by 
* more than one thread. However, if many threads need to generate 
* pseudorandom numbers at a great rate, it may reduce contention 
* for each thread to have its own pseudorandom-number generator. 
* 
* @return a pseudorandom <code>double</code> greater than or equal 
* to <code>0.0</code> and less than <code>1.0</code>. 
* @see  java.util.Random#nextDouble() 
*/ 
public static double random(); 
+1

我讀了Math.random()的文檔,我可以發誓它之前介於0.0和1.0之間。我只是再讀一遍。今天是一個非常漫長的夜晚。 – Naz 2014-11-23 08:06:40

2

否,Math.random()不會返回1.它的包容下界0,而是一個獨家上限爲1.0。從文檔 - 重點礦山:

返回帶有正號,大於或等於0.0和小於 1.0雙精度值。

現在考慮到這是浮點數學,你仍然需要考慮是否有一些小於1的值,例如當乘以6時,最接近的可表示的double是6而不是6以下的某個值。但我不認爲這是一個問題在這裏。

它仍然會更清楚使用java.util.Random雖然....

private static final int SIDES = 6; 

public static void main(String[] args) { 
    Random random = new Random(); 
    int a = random.nextInt(SIDES) + 1; 
    int b = random.nextInt(SIDES) + 1; 
    int sum = a + b; 
    System.out.println(sum); 
} 
+0

'(1 - 2 ** - 53)* 6'加倍小於'6',所以沒關係。 – 2014-11-23 13:45:40

+0

@DavidEisenstat:對 - 這是我懷疑的那種事情*會很好,但從來沒有相信沒有做數學:) – 2014-11-23 13:46:11

1

Math.random()該方法不返回1.0,因爲它具有其邊界在0.0高達但不包括1.0和6相乘和添加1,即(Math.random()*6)+1將在輸入(int)後返回1到6的值。

而且可變雙方可能已被聲明爲final

private static int SIDES = 6; 
+0

你從哪裏得到0.9的綁定? – Henry 2014-11-23 09:13:32

+0

界限0.0最高但不包括1.0 – 2014-11-23 09:23:17

+0

以及0.95或0.991 ......? – Henry 2014-11-23 09:24:11

0

隨機()可以產生足夠接近1的值,但他們將永遠是小於1 這裏的問題是投給( int)從一個正值。結果總是小於6,在{0,1,2,3,4,5}的集合中變化。所以答案是否定的,既不是也不可能是7. 希望這有助於。

爲了證明,運行下面的代碼:

 
    double x=0.99; 
    System.out.println((int)(6*x)); 
播放與x的值,無論是1多麼接近,你仍然會得到5個或更少的印刷。