【发布时间】:2011-12-22 22:54:16
【问题描述】:
如何使用 Math.random 生成随机整数?
我的代码是:
int abc= (Math.random()*100);
System.out.println(abc);
它打印出来的都是0,我该如何解决这个问题?
【问题讨论】:
-
代码真的不应该打印0,它不应该编译。
-
那是什么版本?第一行给了我“类型不匹配:无法将 double 转换为 int”,这是我所期望的。
-
@GworfHi 对于 0 - 100 使用
int abc= (int)Math.random()*101; -
@God Casting
Math.random()不先乘以 101 意味着abc将始终为 0。你必须这样做int abc = (int)(Math.random()*101);