/*
*这个程序演示了Math类和Random类的应用。Math类中全部为静态属性和静态方法。
*/
package com.lwj.demo;
import static java.lang.Math.*;//静态导入
import java.util.*;
public class Math_RandomDemo {
public static void main(String[] args){
System.out.println("E:" + E);// 代数中e的值
System.out.println("PI:" + PI);// π的值
System.out.println();
System.out.println("abs(562.2565):" + abs(562.2565));// 取绝对值
System.out.println("ceil(45.2):" + ceil(45.2));// 取大于或等于参数的最小整数
System.out.println("floor(45.7):" + floor(45.7));// 取小于或等于参数的最大整数
System.out.println("round(45.7):" + round(45.7));// 四舍五入
System.out.println("exp(1.0):" + exp(1.0));// 求e的1次方
System.out.println("log(E):" + log(E));// 求以e为底的对数值(自然对数)
System.out.println("log10(100.0):" + log10(100.0));// 求以10为底的对数值
System.out.println("pow(2.0,3.0):" + pow(2.0, 3.0));// 求几次方
System.out.println("sqrt(9.0):" + sqrt(9.0));// 求平方根
System.out.println("cbrt(8.0):" + cbrt(8.0));// 求立方根
System.out.println("max(20.1,-20.2):" + max(20.1, -20.2));// 求两者中最大值
System.out.println();
System.out.println("toDegrees(PI/2):" + toDegrees(PI / 2));// 由弧度值求度数
System.out.println("toRadians(45.0):" + toRadians(45.0));// 由度数求弧度值
System.out.println("cos(PI/3):" + cos(PI / 3));// 求cos值
System.out.println("acos(0.5):" + acos(0.5));// 求acos值
System.out.println();
System.out.println("random():" + random());// 获得随机数,值在[0.0,1.0)之间;
System.out.println();
System.out.println("————————用Random类创建随机数序列的例子————————");
Random r = new Random();
System.out.println("nextBoolean():" + r.nextBoolean());//返回随机的boolean值
byte[] b=new byte[10];
r.nextBytes(b);//返回随机的字节值(我的理解就是ASCII码)
System.out.print("nextBytes():");
for(int i=0;i<b.length;i++){
System.out.print(" "+b[i]);
}
System.out.println();
System.out.println("nextGaussian():" + r.nextGaussian());//返回标准正态分布下的随机double值,有正有负
System.out.println("nextInt():" + r.nextInt());//返回随机的整数,有正有负
System.out.println("nextInt(100):" + r.nextInt(100));//返回随机的整数,[0,100)之间
System.out.println("nextLong():" + r.nextLong());//返回随机的长整数,有正有负
System.out.println("nextFloat():" + r.nextFloat());//返回随机的float值,[0.0,1.0)之间
System.out.println("nextDouble():" + r.nextDouble());//返回随机的double值,[0.0,1.0)之间
}
}
运行结果为:(随机数每次都不一样)
E:2.718281828459045
PI:3.141592653589793
abs(562.2565):562.2565
ceil(45.2):46.0
floor(45.7):45.0
round(45.7):46
exp(1.0):2.7182818284590455
log(E):1.0
log10(100.0):2.0
pow(2.0,3.0):8.0
sqrt(9.0):3.0
cbrt(8.0):2.0
max(20.1,-20.2):20.1
toDegrees(PI/2):90.0
toRadians(45.0):0.7853981633974483
cos(PI/3):0.5000000000000001
acos(0.5):1.0471975511965979
random():0.27604997662152586
————————用Random类创建随机数序列的例子————————
nextBoolean():true
nextBytes(): 55 30 -16 -83 -25 -14 -126 -89 81 118
nextGaussian():-0.24921657706143702
nextInt():-1559131945
nextInt(100):47
nextLong():6999829418780007826
nextFloat():0.62293845
nextDouble():0.4471403495538354