Java中Math类常用方法总结 + Random类与Math类小结合

288 篇文章 0 订阅
62 篇文章 0 订阅

1、Java中Math类常用方法总结

        Java中Math类常用的方法有:Math.ceil()、 Math.floor()、 Math.round()、 Math.abs()、 Math.sqrt()、 Math.pow();

        Java中Math类中定义的特殊数据有:  Math.PI(圆周率)、 Math.E(自然数);

Java的1.6中文版API下载地址为:Java的1.6中文版API下载地址 


package Test_02;

import java.util.Random;

public class T03_Math {
	public static void main(String[] args) {
		
		System.out.println(Math.ceil(3.2));  //返回值:4.0, 返回最小的(最接近负无穷大)double 值,该值大于等于参数,并等于某个整数。
		System.out.println(Math.floor(3.2));  //返回值:3.0,返回最大的(最接近正无穷大)double 值,该值小于等于参数,并等于某个整数。
		System.out.println(Math.round(3.2));  //返回值:3,返回最接近参数的 int。(四舍五入)
		System.out.println(Math.round(3.8));  //返回值:4,返回最接近参数的 int。(四舍五入)
		System.out.println("--------------------------------");
		
		System.out.println(Math.abs(-45));  //返回值:45,求取绝对值
		System.out.println(Math.sqrt(64));  //返回值:8.0,返回正确舍入的 double 值的正平方根。
		System.out.println(Math.pow(5, 2));  //返回值:25.0, 返回第一个参数的第二个参数次幂的值。
		System.out.println(Math.pow(2, 5));  //返回值:32.0,
		System.out.println("--------------------------------");
		
		System.out.println(Math.PI);  //返回值:3.141592653589793,返回圆周率Π
		System.out.println(Math.E);  //返回值:2.718281828459045,返回比任何其他值都更接近 e(即自然对数的底数)的 double 值。
		System.out.println(Math.exp(2));  //返回值:7.38905609893065,返回 返回欧拉数 e 的 double 次幂的值。
		System.out.println("--------------------------------");
		
		
		
	}
	
	
}


2、Random类与Math类小结合

         注意:仔细体味下段代码中内含的“奇妙 ”,品味Random类于Math类在处理随机数中的异同。


package Test_03;

import java.util.Random;

public class T03_MathAndRandom {
	public static void main(String[] args) {
		
		//调用Math类中方法返回0.0 —— 1.0 之间均匀分布的 double值。
		double d = Math.random();
		System.out.println(d);
		System.out.println("--------------------------------");
		
		//生成:0-10之间的任意整数:
		int a1 = (int)(10 * Math.random());
		System.out.println(a1);
		
		//生成:20-30之间的任意整数:
		int a2 = 20 + (int)(10 * Math.random());
		System.out.println(a2);
		System.out.println("--------------------------------");
		
		//调用Random类中方法返回0.0 —— 1.0 之间均匀分布的 double值。
		Random ran = new Random();
		double d2 = ran.nextDouble();
		System.out.println(d2);
		
		//生成:0-10之间的任意整数:
		int a3 = ran.nextInt(10);
		System.out.println(a3);
		
		//生成:20-30之间的任意整数:
		int a4 = 20 + ran.nextInt(10);
		System.out.println(a4);
		
	}
	
	
}







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值