Math类
包含用于执行基本数学运算的方法,如绝对值,对数,平方根和三角函数。它是一个final类,其中定义的都是一些常量和景甜方法。
常用方法如下:
补充:
1、Math.abs() 计算绝对值
package com.Java.Base;
public class Test_Math {
public static void main(String[] args) {
//Math常用方法
//sqrt开平方
System.out.println("Math.sqrt(4)="+Math.sqrt(4));
//ceil向上取整
System.out.println("Math.ceil(3.3)="+Math.ceil(3.3));
//floor向下取整
System.out.println("Math.floor(3.3)="+Math.floor(3.3));
//pow乘方
System.out.println("Math.pow(2,3)="+Math.pow(2,3));
//round四舍五入
System.out.println("Math.round(2.3)="+Math.round(2.3));
System.out.println("Math.round(2.5)="+Math.round(2.5));
//random() [0,1)
System.out.println("Math.random()="+Math.random());
}
}
运行结果:
java 三种产生随机数方法
1. System.currentTimeMillis() 得到long型数字
2. Math.random() 取值范围为[0,1)
3. Random类产生一个随机数
Random类中实现的随机算法是伪随机的,即有规律的随机。随机时,随机算法的起源数字称为种子数seed,在种子数的基础上进行一定的变换,从而产生需要的随机数字。相同种子数的Random对象,相同次数生成的随机数字相同。
构造方法:
1、public Random() 默认种子数是不一样的
2、public Random(long seed) 自行设定seed
常用函数:
1、public void nextBytes(byte[] bytes)
2、public int nextInt()
3、public int nextInt(int n) 产生[0,5)之间的随机正数
4、public boolean nextBoolean()
5、public float nextFloat()
6、public double nextDouble()
实例:
package com.Java.Base;
import java.util.Arrays;
import java.util.Random;
public class Test_Random {
public static void main(String[] args) {
Random r=new Random();
byte[] b = new byte[5];
r.nextBytes(b);
System.out.println(Arrays.toString(b));
System.out.println(r.nextInt(5));
}
}
结果: