java基础---Math类

来源:互联网 发布:windows xp 光盘镜像 编辑:程序博客网 时间:2024/06/06 09:02

Math简介:Math类位于java核心包中(javalang),调用方法不需要引包,没有构造方法,不能实例化对象。提供了操作数学运算的方法,都是静态的,通过Math.method直接调用。

Math常用方法:
ceil(args) 返回大于参数的最小整数 返回类型为double
floor(args) 返回小于参数的最大整数 返回类型为double
round(args) 返回四舍五入的整数 返回类型为double
pow(a,b) 返回a的b次方 返回类型为double

double d1 = Math.ceil(12.5);double d2 = Math.floor(12.5);double d3 = Math.round(12.5);double d4 = Math.pow(10, 2);System.out.println(d1);System.out.println(d2);System.out.println(d3);System.out.println(d4);

13.0
12.0
13.0
100.0

随机数实现方法:

我们以【1,10)举例
1.Random类实现:
Random类可在实例化后实现整数,双精度浮点数等的随机数操作。

Random r = new Random();        for(int i = 0;i<5;i++){            //nextDouble()方法返回[0,1)的双精度随机数,如果要实现【1,10)的随机数,可以*10并+1后强转为int            int num = (int)(r.nextDouble()*10+1);            System.out.println(num);        }

2
10
4
2
10

等效实现:

int num = r.nextInt(10)+1;//nextInt(int arg0)方法参数为范围限定->[0,args)的整数随机数

2.通过Math类的random()方法实现

for(int i = 0;i<5;i++){            //Math.random()静态方法返回[0,1)的双精度随机数            int num = (int)(Math.random()*10+1);            double d = Math.random();            System.out.println(num+"---"+d);        }

1—0.8195822555665228
3—0.8335365777267785
7—0.819495408915826
9—0.03507351864676833
5—0.015326880399073484