“Java中的随机数”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第17行: | 第17行: | ||
0.0 <= random < 1.0 | 0.0 <= random < 1.0 | ||
+ | |||
+ | |||
+ | |||
+ | === 生成大于等于 m 小于 n 的随机数 === | ||
+ | <syntaxhighlight lang="java"> | ||
+ | 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); | ||
+ | |||
+ | } | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight><syntaxhighlight lang="console"> | ||
+ | 3.3551556765339487 | ||
+ | </syntaxhighlight> |
2022年12月10日 (六) 05:53的版本
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