gpt4 book ai didi

两个骰子的 Java 总和 - 此代码给出的点数是否超过 6?

转载 作者:搜寻专家 更新时间:2023-10-31 20:11:12 26 4
gpt4 key购买 nike

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 的在线网站上的“Introduction to Programming with Java”一书中获取了这段代码。

我只是想问 ab 如果碰巧 Math.random( )1.0?还是我错了?

1.0 * 6 + 1 = 7?

最佳答案

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

关于两个骰子的 Java 总和 - 此代码给出的点数是否超过 6?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27086845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com