从零开始学java(三十-八)--Math类的简单使用

从零开始学java(三十-八)--Math类的简单使用


java.lang.Math提供了一系列静态方法用于科学计算;其方法的参数和返回值类型一般为double型。如果需要更加强大的数学运算能力,计算高等数学中的相关内容,可以使用apache commons下面的Math类库。

Math类的常用方法:

  1. abs 绝对值

  2. acos,asin,atan,cos,sin,tan 三角函数

  3. sqrt 平方根

  4. pow(double a, double b) a的b次幂

  5. max(double a, double b) 取大值

  6. min(double a, double b) 取小值

  7. ceil(double a) 大于a的最小整数

  8. floor(double a) 小于a的最大整数

  9. random() 返回 0.0 到 1.0 的随机数

  10. long round(double a) double型的数据a转换为long型(四舍五入)

  11. toDegrees(double angrad) 弧度->角度

  12. toRadians(double angdeg) 角度->弧度

代码示例

package Math类;

import java.util.Random;

public class TestMath {

	public static void main(String[] args) {
		//Math类取整的相关操作
		System.out.println(Math.ceil(3.2));//取大于的最靠近的整数
		System.out.println(Math.floor(5.6));//取小于的最靠近整数
		System.out.println(Math.round(9.1));//四舍五入
		System.out.println(Math.round(9.6));//四舍五入
		
		//绝对值,开放,a的b次方等操作
		System.out.println(Math.abs(-65));//取绝对值
		System.out.println(Math.sqrt(9));//取二次方根
		System.out.println(Math.pow(2, 5));//2的5次方操作
		
		//Math类中的常用常量Π和e
		System.out.println(Math.E);
		System.out.println(Math.PI);
		
		//获得一个[0,1)的随机数
		System.out.println(Math.random());
		
		//=====================================================
		//====================================================
		//=====================================================
		//random类详解
		Random random = new Random();
		
		//随机生成[0,1)之间的double类型的数据
        System.out.println(random.nextDouble());
        
        //随机生成int类型允许范围之内的整型数据
        System.out.println(random.nextInt());
        
        //随机生成[0,1)之间的float类型的数据
        System.out.println(random.nextFloat());
        
        //随机生成false或者true
        System.out.println(random.nextBoolean());
        
        //随机生成[0,10)之间的int类型的数据
        System.out.print(random.nextInt(10));
        
        //随机生成[20,30)之间的int类型的数据
        System.out.print(20 + random.nextInt(10));
        
        //随机生成[20,30)之间的int类型的数据(此种方法计算较为复杂)
        System.out.print(20 + (int) (random.nextDouble() * 10));
        
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值