public class Test { public static void main(String[] args) {
System.out.println(Math.random());
System.out.println((int) ((((Math.random()) * 11)) - 1));
}}
运行结果为:
0.6056141990830389
4
为什么不是
0.6056141990830389
5呢?谢谢解答
System.out.println(Math.random());
System.out.println((int) ((((Math.random()) * 11)) - 1));
}}
运行结果为:
0.6056141990830389
4
为什么不是
0.6056141990830389
5呢?谢谢解答
建议你这样输出看看
public class Test {public static void main(String[] args) {
double a=Math.random();
System.out.println(a);
double b=Math.random();
System.out.println(b);
System.out.println((int) (((b * 11)) - 1));
}}
double d;
d=Math.random();
System.out.println(d);
System.out.println((int) (((d * 11)-1) ));
}
}
你调用了两次随机函数,两次值不同。
public class Test {public static void main(String[] args) {
System.out.println(Math.random());
System.out.println((int) ((Math.random());
}}
{
if(((int) ((((Math.random()) * 11)) - 1))==-1) break;
}
System.out.println("xxxxxx");- -
static double random()
返回带正号的 double 值,该值大于等于 0.0 且小于 1.0。
这是源码 private static Random randomNumberGenerator; private static synchronized void initRNG() {
if (randomNumberGenerator == null)
randomNumberGenerator = new Random();
}
public static double random() {
if (randomNumberGenerator == null) initRNG();
return randomNumberGenerator.nextDouble();
}
API中Random类的nextDouble()
nextDouble()
返回下一个伪随机数,它是取自此随机数生成器序列的、在 0.0 和 1.0 之间均匀分布的 double 值。(((Math.random()) * 11)) 这个范围 不应该是0.-10.0
不应该是0.-10.0
应该是[0,11)能等0,但不能等11
(Math.random()) * 11)-1 产生数的范围[0,10]
所以不会产生-1
还有概率貌似太小了点,0到1之间那么多小数可想而知
纯属猜测 等大神
public static void main(String[] args) {
while(true){
double randNum=Math.random();
System.out.println(randNum);
if(randNum==0)
break;
}
}理论和实际的反差很大呀
double能精确到
0.28690923110976096
0.08907824126186559
0.26195537980015315
...
多位(自己没数),想在一定时间内出现0,好像不太可能.
按你那个程序的写法,取到-1是完全不可能的,因为你设计到了double向int的强制类型转化,假设Math.random()生成了一个很接近于零(但比零大),假设再乘以11减去1得到的数是-0.99999999999
然后转化为int,(int)-0.99999999999的转化结果是0而不是-1
所以你写这个程序计算的数字最小就是0