天天看点

Math 类的使用示例

Math 类的使用示例

package com.math;

import org.junit.Test;

/**
 * Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和
  * 三角函数。 该类位于 java.lang 包下,提供了一系列静态方法用于科学计
  * 算,其方法的参数和返回值类型一般为 double 型。
 */
public class MathTest {
	@Test
	public void test() {
		// 产生随机数
		double random = Math.random(); // 会产生(0,1)之间随机数
		System.out.println(random);
		
		double v = 2.5;
		// round()方法是四舍五入
		System.out.println(Math.round(v)); // 3
		v = -2.5;
		System.out.println(Math.round(v)); // -2
		
		System.out.println("--------");
		
		// floor() 返回比指定数小的最大的整数
		v = 2.1;
		System.out.println(Math.floor(v)); // 2
		v = -2.1;
		System.out.println(Math.floor(v)); // -3
		
		System.out.println("--------");
		
		// ceil()方法返回比指定数大的最小的整数
		v = 2.1;
		System.out.println(Math.ceil(v)); // 3
		v = -2.1;
		System.out.println(Math.ceil(v)); // -2
		
		System.out.println("--------");
		
		System.out.println(Math.abs(v)); // 2.1
	}
}