Java学习之Math常用API

       在日常处理数据时总会涉及到数据的计算,但是在java中有些运算符甚至是专用符号,有些呢则是识别不了,而java官方提供了很多关于数学计算的API方法,且都是静态的,可以直接通过类名调用,下面列几个常用的API方法

  • static E abs (E e): 此处E只能指double、float、int、long 四种数据类型且与返回值类型保持一致 作用是返回E类型的绝对值

示例代码:

public static void main(String[] args) {
		int num1 = Math.abs(-3);
		System.out.println(num1);
		float num2 = Math.abs(- 0.3f);
		System.out.println(num2);
		double num3 = Math.abs(- 3.5);
		System.out.println(num3);
		long num4 = Math.abs(-4354l);
		System.out.println(num4);
}

 结果展示:

  • static E max(E e1, E e2): 此处E只能指double、float、int、long四种数据类型且两个数据的数据类型和返回值类型需保持一致,作用是返回两个数中较大的数

示例代码:

public static void main(String[] args) {
		System.out.println(Math.max(3, 4));// int型
		System.out.println(Math.max(1.2f, 2.0f));// float型
		System.out.println(Math.max(4.5d, 2.5d));// double型
		System.out.println(Math.max(432l, 532l));// long型
	}

结果展示:

  • static E min(E e1, E e2): 此处E只能指double、float、int、long四种数据类型且两个数据的数据类型和返回值类型需保持一致,作用是返回两个数中较小的数

示例代码:

public static void main(String[] args) {
		System.out.println(Math.min(3, 4));// int型
		System.out.println(Math.min(1.2f, 2.0f));// float型
		System.out.println(Math.min(4.5d, 2.5d));// double型
		System.out.println(Math.min(432l, 532l));// long型
	}

结果展示:

  • static double pow(double b1, double b2): 作用是返回b1的b2次幂值

示例代码:

public static void main(String[] args) {
		System.out.println(Math.pow(2,3));// 求2的3次方
        // 注意:返回的值是double类型
	}

结果展示:

  • static long round(double e): 作用是返回最接近参数的long类型值(符合四舍五入) 向上取整

示例代码:

public static void main(String[] args) {
		System.out.println(Math.round(4.4d));// double类型值取整
		System.out.println(Math.round(4.5d));
	}

结果展示:

  • static int round(float e): 作用是返回最接近参数的int类型值(符合四舍五入)向上取整

示例代码:

public static void main(String[] args) {
		System.out.println(Math.round(1.4f));// float类型值取整
		System.out.println(Math.round(-4.5f));
	}

结果展示:

  • static double sqrt(double b): 返回正确舍入的double值的正平方根 

示例代码:

public static void main(String[] args) {
		System.out.println(Math.sqrt(4.0));
		System.out.println(Math.sqrt(6));
		// 注意:参数数据类型和返回值数据类型都是double
	}

结果展示:

  • static double random():  返回一个[0 , 1.0) 之间的伪随机double值

示例代码:

public static void main(String[] args) {
		System.out.println(Math.random());//  返回[0,1.0)
		System.out.println(Math.random());
		System.out.println(Math.random());
		System.out.println(Math.random());
	}

结果展示:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值