Math类提供了运算符如绝对值,平方,开方,三角函数,对数等,还包括π和e等常数
实例程序:
package standardClasses;
import static java.lang.Math.*;
/*
the statuc import construct allows you to use the static method
of a class without the class name refix
*/
public class TheMathClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(abs(-5)); //return the absolute value
//equavelent to:
System.out.println(Math.abs(-5));
System.out.println(abs(-4.5));
System.out.println(pow(5, 10)); //return base(first) ^ exp(second), base >= 0 exp is an integer
System.out.println(sqrt(25)); //return the square root
System.out.println(random()); //return a random number between 0 and 1
System.out.println(PI); //comstant π
System.out.println(E); //constant e
}
}
Math类所有的函数和常数都是静态方法,因此不存在Math对象
静态引入可以在不加类名前缀使用一个类里面的静态方法。如在Math类使用静态引入import static java.lang.Math.*;
允许直接写函数名,而非Math.函数
随机数
Math.random();
该函数可以生成0。0至1。0的随机数,包括0.0,但不包括1.0.
可以移动或者扩大该范围,如:
//test random number
System.out.println(6 * Math.random()); //0.0 <= x < 6.0
System.out.println(Math.random() + 2); //2.0 <= x < 3.0
System.out.println(2 * Math.random() + 5); //5.0 <= x < 7.0
//general form
int highValue = 8;
int lowValue = 5;
double x = (highValue - lowValue) * Math.random() + lowValue; //lowValue <= x < highValue
随机整数
把随机数结果强转为int可以得到任意随机整数
其中Math.random()所乘的数叫做scaling factor
//test random integer
System.out.println((int)(Math.random() * 100)); //integer from 0 to 99
int a = (int)Math.random() * 100; //error: always zero, because casting is prior to multiply
//general approach
int k = 20; //k is called scaling factor
System.out.println((int)(Math.random() * k));