Java中的随机数

来自姬鸿昌的知识库
跳到导航 跳到搜索

Math.random()

public class Test {

    public static void main(String[] args) {

        double random = Math.random();

        System.out.println(random);

    }

}
0.8981455972172399

[0.0,1.0)

0.0 <= random < 1.0


生成大于等于 m 小于 n 的随机数

public class Test1 {

    public static void main(String[] args) {

        int m = 1;
        int n = 5;

        double random = Math.random() * (n - m) + m;

        System.out.println(random);

    }

}
3.3551556765339487