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编程入门”一书中摘取了这段代码。
我只想问一下,如果a或b是1.0,那么Math.random()是否可能高于6呢?还是我做错了?
1.0 *6+1= 7?
发布于 2014-11-23 08:05:08
Math.random()不能返回1.0,所以a或b不能是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();发布于 2014-11-23 08:06:58
不,Math.random()永远不会返回1。它有一个包含0的下界,但有一个排他性的上界为1.0。从文件中-重点是我:
返回一个带有正号的双值,大于或等于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);
}发布于 2014-11-23 09:09:47
Math.random()方法不返回1.0,因为它的边界为0.0,但不包括1.0,并乘以6并向其添加1,也就是说,(Math.random()*6)+1在键入(int)后将返回1到6的值。
另外,可变边也可以声明为最终。
private static int SIDES = 6;https://stackoverflow.com/questions/27086845
复制相似问题