我编写了一个函数来生成Long.MIN_VALUE和Long.MAX_VALUE之间的随机长值,但它总是返回Long.MIN_VALUE,为什么?
public static long randomLong() {
return (long) (Math.random()*(Long.MAX_VALUE-Long.MIN_VALUE)+Long.MIN_VALUE);
}
感谢您帮助我
答案 0 :(得分:2)
问题是你的长期价值已经溢出。由于Long.MIN_VALUE
对于有符号长整数为负,因此Long.MAX_VALUE-Long.MIN_VALUE
大于Long.MAX_VALUE
,因此在中间计算期间不适合长整数。
请尝试使用nextLong:
public static long randomLong() {
Random ran = new Random();
return ran.nextLong();
}
答案 1 :(得分:2)
由于溢出,Long.MAX_VALUE - Long.MIN_VALUE
的结果为-1
。该值乘以Math.random()
,0.0
包含和1.0
排除值之间的值。它是double
,Long.MIN_VALUE
被添加到-1.0
和0.0
之间的值,结果仍为Long.MIN_VALUE
。与double
相比,Long.MIN_VALUE
不够精确,无法添加如此之小的内容,因此结果为Long.MIN_VALUE
double
。
要检索均匀分布的随机long
,请使用Random
类及其method nextLong()
。
// This Random object can be stored in the class for reuse
Random rnd = new Random();
然后:
return rnd.nextLong();