Math類是一個數學類
包含執行基本數字運算的方法,如基本指數,對數,平方根和三角函數
這個類的方法都是靜態的所以可以通過 Math.方法名();
調用.
例子:
Math.abs(數據類型 a);
絕對值方法(有int, float, double, long類型)
public class Demo {
public static void main(String[] args) {
//這裏用int類型舉例子
int a1 = Math.abs(-1);
int a2 = Math.abs(-5);
int a3 = Math.abs(3);
sop("a1="+a1);
sop("a2="+a2);
sop("a3="+a3);
}
//不太想寫太多輸出,就把輸出封裝起來了
public static void sop(String string) {
System.out.println(string);
}
}
輸出結果:
常用的方法:
Math.ceil(); 返回大於參數的最小整數
Math.floor(); 返回小於參數的最大整數
Math.round(); 返回四捨五入的整數
Math.pow(a, b); a的b次方
返回值都是 double類型
例子:
public class Demo {
public static void main(String[] args) {
double d1 = Math.ceil(11.56); // 12是11.56最小的整數
double d2 = Math.floor(11.56); // 11是11.56最大的整數
double d3 = Math.round(11.56); // 11.56的四捨五入是 6大於等於5 於是變成了11.60, 同樣6大於等5 所以變成了12
double d4 = Math.pow(10,2); //10的2次方
sop("d1="+d1);
sop("d2="+d2);
sop("d3="+d3);
sop("d4="+d4);
}
public static void sop(String string) {
System.out.println(string);
}
}
運行結果:
一個取隨機值的方法
Math.random() 返回一個大於等於0.0小於1.0的double類型的僞隨機數
例子:
public class Demo {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) { //隨機產生10個隨機數
double d = Math.random();
System.out.println(d);
}
}
}
運行結果:
如果我們想要1-10的隨機數可以這樣–用ceil()
方法獲取大於它的最小整數,以及random()
方法乘10.
例子:
public class Demo {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
double d = Math.ceil(Math.random()*10);
System.out.println(d);
}
}
}
運行結果:
也可以用
double d = Math.floor(Math.random()*10+1);
來獲取1到10的隨機數.
有一個類專門封裝了隨機數方法的類—Random
這個方法不是靜態的, 所以需要new 對象.
例子:
import java.util.Random; //導包
public class Demo {
public static void main(String[] args) {
Random r = new Random();
for(int i=0; i < 6; i++) {
int a = r.nextInt(6)+1;
System.out.println(a);
}
}
}
運行結果:
Random類還有諸如 nextFolat()
, nextDouble()
等方法, 可以看API.
Math類中還有 max(a,b);
min(a,b);
等方法, 可以看API玩一玩.