java如何生成随机数

1.使用Math方法,

Math.random()随机生成一个double类型[0,1)(包括0,不包括1,带有争议),如果想生成1~N的随机数:

int num = (int)(Math.random()*N);
  1. 向上取整:Math.ceil(double a);

  1. 向下取整:Math.floor(double a);

  1. 四舍五入:Math.round(double a);

2.使用Random类来生成随机数
package Scanner;

import java.util.Random;

public class 随机数 {
    public static void main(String[] args) {
        Random r = new Random();
        while (true){
            //生成一个包括0,不包括设置的数
            System.out.println(r.nextInt(3));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zouzxxi/article/details/129296140