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

来自姬鸿昌的知识库
跳到导航 跳到搜索
第37行: 第37行:
 
</syntaxhighlight><syntaxhighlight lang="console">
 
</syntaxhighlight><syntaxhighlight lang="console">
 
3.3551556765339487
 
3.3551556765339487
 +
</syntaxhighlight>
 +
 +
 +
 +
 +
=== Random类 ===
 +
 +
==== 伪随机整数 ====
 +
<syntaxhighlight lang="java">
 +
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);
 +
    }
 +
}
 +
</syntaxhighlight><syntaxhighlight lang="console">
 +
伪随机整数:-240205213
 +
</syntaxhighlight>
 +
 +
==== 限制最大值的伪随机非负整数 ====
 +
<syntaxhighlight lang="java">
 +
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);
 +
    }
 +
}
 +
</syntaxhighlight><syntaxhighlight lang="console">
 +
得到的小于 10 的非负伪随机整数是:6
 
</syntaxhighlight>
 
</syntaxhighlight>

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

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