Math类是一个数学类
包含执行基本数字运算的方法,如基本指数,对数,平方根和三角函数
这个类的方法都是静态的所以可以通过 Math.方法名();
调用.
例子:
Math.abs(数据类型 a);
绝对值方法(有int, float, double, long类型)
public class Demo {
public static void main(String[] args) {
//这里用int类型举例子
int a1 = Math.abs(-1);
int a2 = Math.abs(-5);
int a3 = Math.abs(3);
sop("a1="+a1);
sop("a2="+a2);
sop("a3="+a3);
}
//不太想写太多输出,就把输出封装起来了
public static void sop(String string) {
System.out.println(string);
}
}
输出结果:
常用的方法:
Math.ceil(); 返回大于参数的最小整数
Math.floor(); 返回小于参数的最大整数
Math.round(); 返回四舍五入的整数
Math.pow(a, b); a的b次方
返回值都是 double类型
例子:
public class Demo {
public static void main(String[] args) {
double d1 = Math.ceil(11.56); // 12是11.56最小的整数
double d2 = Math.floor(11.56); // 11是11.56最大的整数
double d3 = Math.round(11.56); // 11.56的四舍五入是 6大于等于5 于是变成了11.60, 同样6大于等5 所以变成了12
double d4 = Math.pow(10,2); //10的2次方
sop("d1="+d1);
sop("d2="+d2);
sop("d3="+d3);
sop("d4="+d4);
}
public static void sop(String string) {
System.out.println(string);
}
}
运行结果:
一个取随机值的方法
Math.random() 返回一个大于等于0.0小于1.0的double类型的伪随机数
例子:
public class Demo {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) { //随机产生10个随机数
double d = Math.random();
System.out.println(d);
}
}
}
运行结果:
如果我们想要1-10的随机数可以这样–用ceil()
方法获取大于它的最小整数,以及random()
方法乘10.
例子:
public class Demo {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
double d = Math.ceil(Math.random()*10);
System.out.println(d);
}
}
}
运行结果:
也可以用
double d = Math.floor(Math.random()*10+1);
来获取1到10的随机数.
有一个类专门封装了随机数方法的类—Random
这个方法不是静态的, 所以需要new 对象.
例子:
import java.util.Random; //导包
public class Demo {
public static void main(String[] args) {
Random r = new Random();
for(int i=0; i < 6; i++) {
int a = r.nextInt(6)+1;
System.out.println(a);
}
}
}
运行结果:
Random类还有诸如 nextFolat()
, nextDouble()
等方法, 可以看API.
Math类中还有 max(a,b);
min(a,b);
等方法, 可以看API玩一玩.