“Java中的随机数”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
第74行: 第74行:
 
得到的小于 10 的非负伪随机整数是:6
 
得到的小于 10 的非负伪随机整数是:6
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
==== 获取其他随机值 ====

2022年12月10日 (六) 06:07的版本

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 的伪随机双精度浮点数

1 <= random < 5

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



Random类

伪随机整数

import java.util.Random;

public class Test2 {
    public static void main(String[] args) {
        Random random = new Random();
        int nextInt = random.nextInt();
        System.out.printf("伪随机整数:%d\n", nextInt);
    }
}
伪随机整数:-240205213

限制最大值的伪随机非负整数

import java.util.Random;

public class Test3 {
    public static void main(String[] args) {
        int lt = 10;
        Random random = new Random();
        int nextInt = random.nextInt(lt);
        System.out.printf("得到的小于 %d 的非负伪随机整数是:%d\n", lt, nextInt);
    }
}
得到的小于 10 的非负伪随机整数是:6

获取其他随机值