java Math.round() 随机数

2025-03-13 23:58:01
推荐回答(5个)
回答1:

我先问个问题,生成随机数的方法是round么? 是random吧?

这里有2个办法,一个是用Math,另一个是用Random类。

1、Math类
DecimalFormat df = new DecimalFormat("000");
int temp = (int) Math.random()*1000;
String randomNum = df.format(temp);
System.out.println(randomNum);

2、Random类
DecimalFormat df = new DecimalFormat("000");
Random r = new Random();
int temp = r.nextInt(1000);
String randomNum = df.format(temp);
System.out.println(randomNum);

回答2:

nextInt(int n)
返回一个伪随机数,它是取自此随机数生成器序列的、在 0(包括)和指定值(不包括)之间均匀分布的 int 值。
因此可以:
System.out.println(new Random().nextInt(999));

回答3:

能不能用别的函数啊!
public static void main(String[] args) {
Random r = new Random() ;
String s="";
for(int i=0;i<3;i++){
s=s+r.nextInt(10);
}
System.out.println(s);
}

回答4:

(int)(Math.round() *100)

这样来试试

回答5:

楼上少写了,x<(int)(Math.random() *1000)&&x>(int)(Math.random())