目录
- Math.random用法
- 获取1-100之间的随机数
- 获取m~n之间的随机数
- double保留三位小数
一:Math.random用法
public static double random()
返回一个 double值与一个积极的迹象,大于或等于 0.0小于 1.0。返回值与选择伪随机(大约),范围分布均匀。
二: 获取1-100之间的随机数
public static int getRandom(){
return (int)(Math.random()*100)+1;
}
三:获取[m,n]之间的随机数
-
小数
Math.random()*(右-左)+左
-
整数
Math.random()*(右-左+1)+左
import java.util.Arrays;
public class TestRandom {
public static void main(String[] args) {
int[] a = new int[6];
for(int i=0;i<1000000;i++){
// // [1.2,3.3] 随机数
// // double x = Math.random()*(3.3-1.2)+1.2;
// double x = Math.random()*(1.2-0.5)+0.5;
// System.out.println(x);
// if(x>1.2||x<0.5){
// System.out.println(x);
// }
// [1,5]的随机值
double x = Math.random()*(5-1+1)+1;
System.out.println((int)x);
a[(int)x]++;
}
System.out.println(Arrays.toString(a));
}
}
四: double保留三位小数
double d = Double.valueOf(String.format("%.3f",Math.random()));
五:的其他方法
1> 换底公式
2> ceil、round、floor、pow
public class Main{
public static void main(String[] args) {
double a = 2.5;
System.out.println(Math.ceil(a)); // 3.0
System.out.println(Math.round(a)); // 3
System.out.println(Math.floor(a)); // 2.0
System.out.println(Math.log(4)); // 1.3862943611198906
System.out.println(Math.log(4)/Math.log(2)); // 2.0
System.out.println(Math.pow(2.5,2.5)); // 9.882117688026186
}
}