两个骰子的Java总和 - 这个代码是否会超过6?

时间:2014-11-23 08:04:03

标签: java algorithm

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);
    }
}

我从书中采用了这段代码" Java编程简介"由Sedgewick在他们的在线网站上。

我只是怀疑ab是否可能高于6,如果偶然Math.random()1.0?或者我错了吗?

1.0 * 6 + 1 = 7?

4 个答案:

答案 0 :(得分:2)

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 :(得分:1)

不,Math.random()永远不会返回1.它的包含下限为0,但独占的上限为1.0。从文档 - 强调我的:

  

返回带有正号的double值,大于或等于0.0且小于 1.0。

现在假设这是浮点数学,你仍然需要考虑是否有一些小于1的值,这样当乘以6时,最接近的可表示的双精度数为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);
}

答案 2 :(得分:1)

Math.random()方法不返回1.0,因为它的边界值为0.0,但不包括1.0,乘以6并加1,即(Math.random()*6)+1将返回1到1的值输入(int)后输出6。

此外,可变边可能已被宣布为最终

private static int SIDES = 6;

答案 3 :(得分:0)

random()可能产生足够接近1的值,但它们总是小于1。 这里的问题是从正双精度转换为(int)。结果总是小于6,在{0,1,2,3,4,5}的集合中变化。所以答案是否定的,无论是也不可能是7。 希望这会有所帮助。

要证明,请运行以下代码:     

    double x=0.99;
    System.out.println((int)(6*x));
    
使用x值进行游戏,无论它与1的接近程度如何,您仍然可以获得5或更少的打印。