Math类
- Math.PI——圆周率
- Math.E——e的常量
- Math.abs——求绝对值
- Math.sin/asin/cos/acos/tan/atan/atan2 正弦/反正弦/余弦/反余弦/正切/反正切/商的反正切
- Math.toDegrees 弧度转化角度 Math.toRadians 角度转化为弧度
- Math.ceil——返回这个数四舍五入(入)后的最大值 double类型
System.out.println(Math.ceil(-10.1));//-10.0
System.out.println(Math.ceil(10.7)); //11.0
- Math.floor——返回这个数四舍五入(舍)后的最小值
System.out.println(Math.ceil(-10.1));//-11.0
System.out.println(Math.ceil(10.7)); //10.0
- Math.IEEEremainder——求余
- Math.max/min——最大最小
- Math.sqrt——计算平方根
- Math.cbrt——计算立方根
- Math.pow(num,i)——求n的i次方
- Math.exp——求e的任意次方
- Math.log10——以10为底的对数
- Math.rint——四舍五入,返回double
- .5的时候会取偶数
System.out.println(Math.rint(10.1)); //10.0
System.out.println(Math.rint(10.7)); //11.0
System.out.println(Math.rint(11.5)); //12.0 取偶数
System.out.println(Math.rint(10.5)); //10.0 取偶数
System.out.println(Math.rint(10.51)); // 11.0
System.out.println(Math.rint(10.5)); // -10.0 取偶数
- Math.round——四舍五入,float时返回int型,double时返回long型
System.out.println(Math.round(10.51)); //11
// 注意: 大于五全部加,等于五正数加,小于五全不加
System.out.println(Math.round(-10.5)); //-10
System.out.println(Math.round(-10.51)); //-11
System.out.println(Math.round(-10.2)); // -10
- Math.random——返回0,1之间的随机数 double
4、Random类
java.lang.Math.Random
- 调用Math.Random()可以返回带正号的double值,该值[0.0,1.0)
publicstaticvoidmain(String[] args) {
// 结果是个double类型的值,区间为[0.0,1.0)
System.out.println("Math.random()="+Math.random());
intnum= (int) (Math.random() *3);
// 取值范围变成了[0,3)
// 注意不要写成(int)Math.random()*3,这个结果为0或1,因为先执行了强制转换
System.out.println("num="+num);
}
//结果
//Math.random()=0.44938147153848396
//num=1
java.util.Random类
- 可以产生boolean、int、long、double、byte数组的随机数
- 重子数相同的Random对象生成的随机数序列一样
- Random():创建一个新的随机数生成器,使用一个和系统时间相对应的数字作为种子数
- Random(long seed):使用单个long种子创建一个新的随机数生成器(在创建对象的时候可以给定任意一个合法的种子数,种子数只是随机算法的起源数字,和生成的随机数的区间没有任何关系)
publicstaticvoidmain(String[] args) {
Randomrand=newRandom();
inti=rand.nextInt(100); // 随机生成[0,100)的int整数
System.out.println(i);
}
- nextDouble() nextInt() nextBoolean() nextLong() nextFloat()等方法同理
- nextBytes(byte[] bytes):生成随机字节并将其置于用户提供的 byte 数组中。
publicstaticvoidmain(String[] args) {
Randomran1=newRandom(25);
System.out.println("使用种子为25的Random对象生成[0,100)内随机整数序列: ");
for (inti=0; i<10; i++) {
System.out.print(ran1.nextInt(100) +" ");
}
System.out.println();
// 使用相同种子的Random对象,生成的随机数序列一样
Randomran2=newRandom(25);
System.out.println("使用种子为25的Random对象生成[0,100)内随机整数序列: ");
for (inti=0; i<10; i++) {
System.out.print(ran2.nextInt(100) +" ");
}
System.out.println();
}
void setSeed(long seed)
重新设置一个long类型的Random对象的种子数