您的位置:首页 > 编程语言 > Java开发

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

2017-03-03 12:51 267 查看

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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: