首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >两个骰子的Java和-这个代码会给出上面的A6吗?

两个骰子的Java和-这个代码会给出上面的A6吗?
EN

Stack Overflow用户
提问于 2014-11-23 08:04:02
回答 3查看 223关注 0票数 5
代码语言:javascript
复制
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编程入门”一书中摘取了这段代码。

我只想问一下,如果ab1.0,那么Math.random()是否可能高于6呢?还是我做错了?

1.0 *6+1= 7?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-11-23 08:05:08

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

代码语言:javascript
复制
/**
 * 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();
票数 2
EN

Stack Overflow用户

发布于 2014-11-23 08:06:58

不,Math.random()永远不会返回1。它有一个包含0的下界,但有一个排他性的上界为1.0。从文件中-重点是我:

返回一个带有正号的双值,大于或等于0.0,小于 1.0。

既然这是浮点数学,你仍然需要考虑是否有一些值小于1,以至于当乘以6时,最接近可表示的双值是6,而不是小于6的值……但我不认为这是个问题。

不过,使用java.util.Random还是比较清楚的.

代码语言:javascript
复制
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);
}
票数 1
EN

Stack Overflow用户

发布于 2014-11-23 09:09:47

Math.random()方法不返回1.0,因为它的边界为0.0,但不包括1.0,并乘以6并向其添加1,也就是说,(Math.random()*6)+1在键入(int)后将返回1到6的值。

另外,可变边也可以声明为最终。

代码语言:javascript
复制
private static int SIDES = 6;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27086845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档