“Java中的随机数”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第76行: | 第76行: | ||
==== 获取其他随机值 ==== | ==== 获取其他随机值 ==== | ||
+ | <syntaxhighlight lang="java"> | ||
+ | import java.util.Random; | ||
+ | |||
+ | public class Test4 { | ||
+ | |||
+ | public static void main(String[] args) { | ||
+ | Random random = new Random(); | ||
+ | |||
+ | double nextDouble = random.nextDouble(); | ||
+ | System.out.println(nextDouble); | ||
+ | System.out.printf("nextDouble:%f\n", nextDouble); | ||
+ | |||
+ | long nextLong = random.nextLong(); | ||
+ | System.out.printf("nextLong:%d\n", nextLong); | ||
+ | |||
+ | boolean nextBoolean = random.nextBoolean(); | ||
+ | System.out.printf("nextBoolean:%b\n", nextBoolean); | ||
+ | |||
+ | } | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight><syntaxhighlight lang="console"> | ||
+ | 0.6720388983690521 | ||
+ | nextDouble:0.672039 | ||
+ | nextLong:5729745496854116442 | ||
+ | nextBoolean:true | ||
+ | </syntaxhighlight> |
2022年12月10日 (六) 06:15的版本
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
获取其他随机值
import java.util.Random;
public class Test4 {
public static void main(String[] args) {
Random random = new Random();
double nextDouble = random.nextDouble();
System.out.println(nextDouble);
System.out.printf("nextDouble:%f\n", nextDouble);
long nextLong = random.nextLong();
System.out.printf("nextLong:%d\n", nextLong);
boolean nextBoolean = random.nextBoolean();
System.out.printf("nextBoolean:%b\n", nextBoolean);
}
}
0.6720388983690521
nextDouble:0.672039
nextLong:5729745496854116442
nextBoolean:true