第三十一章 Math類
作者:張子默
一、概述
java.lang.Math
類包含用於執行基本數學運算的方法,如初等指數、對數、平方根和三角函數。類似這樣的工具類,其所有方法均爲靜態方法,並且不會創建對象,調用起來非常簡單。
二、基本運算的方法
-
public static double abs(double a)
:返回參數的絕對值double d1 = Math.abs(-5); //d1的值爲5 double d2 = Math.abs(5); //d2的值爲5
-
public static double ceil(double a)
:返回大於等於參數的最小整數double d1 = Math.ceil(3.3); //d1的值爲4.0 double d2 = Math.ceil(-3.3); //d2的值爲-3.0 double d3 = Math.ceil(5.1); //d3的值爲6.0
-
public static double floor(double a)
:返回小於等於參數的最大整數double d1 = Math.floor(3.3); //d1的值爲3.0 double d2 = Math.floor(-3.3); //d2的值爲-4.0 double d3 = Math.floor(5.1); //d3的值爲5.0
-
public static long round(double a)
:返回最接近參數的long(相當於四捨五入方法)long d1 = Math.round(5.5); //d1的值爲6 long d2 = Math.round(5.4); //d2的值爲5
實例
/*
java.util.Math類是數學相關的工具類,裏面提供了大量的靜態方法,完成與數學運算相關的操作
public static double abs(double num):獲取絕對值,多種重載
public static double ceil(double num):向上取整
public static double floor(double num):向下取整
public static long round(double num):四捨五入
Math.PI代表近似的圓周率常量
*/
public class Demo01Math {
public static void main(String[] args) {
//獲取絕對值
System.out.println(Math.abs(3.14)); // 3.14
System.out.println(Math.abs(0)); // 0
System.out.println(Math.abs(-2.5)); // 2.5
System.out.println("==========");
//向上取整
System.out.println(Math.ceil(3.9)); // 4.0
System.out.println(Math.ceil(3.1)); // 4.0
System.out.println(Math.ceil(3.0)); // 3.0
System.out.println("==========");
//向下取整,抹零
System.out.println(Math.floor(30.1)); // 30.0
System.out.println(Math.floor(30.9)); // 30.0
System.out.println(Math.floor(31.0)); // 31.0
System.out.println("==========");
System.out.println(Math.round(20.4)); // 20
System.out.println(Math.round(10.5)); // 11
}
}
三、練習
/*
題目:計算在-10到5.9之間,絕對值大於6或者小於2.1的整數有多少個?
分析:
1.既然已經確定了範圍,for循環
2.起點位置-10.8應該轉換爲-10.0,兩種方法:
2.1 可以使用Math.ceil方法,向上(正方向)取整
2.2 強轉稱爲int,自動捨棄所有小數位
3.每一個數字都是整數,所以不僅表達式應該是num++,這樣每次都死+1的
4.如何拿到絕對值:Math.abs方法
5.一旦發現了一個數字,需要讓計數器++進行統計
備註:如果使用Math.ceil方法,-10.8可以變成-10.0。注意double也是可以進行++的
*/
public class Demo02MathPractise {
public static void main(String[] args) {
int count = 0; //符合要求的數量
double min = -10.8;
double max = 5.9;
//這樣處理,變量i就死區間之內所有的整數
for(int i=(int)min; i<max; i++) {
int abs = Math.abs(i); //絕對值
if(abs>6 || abs<2.1) {
//System.out.println(i);
count++;
}
}
System.out.println("總共有:" + count + "個"); //總共有:9個
}
}
或者
public class MathTest {
public static void main(String[] args) {
// 定義最小值
double min = ‐10.8;
// 定義最大值
double max = 5.9;
// 定義變量計數
int count = 0;
// 範圍內循環
for (double i = Math.ceil(min); i <= max; i++) {
// 獲取絕對值並判斷
if (Math.abs(i) > 6 || Math.abs(i) < 2.1) {
// 計數
count++;
}
}
System.out.println("個數爲: " + count + " 個");
}
}