標籤:exti 內容 oid 能力 運算 產生隨機數 靜態方法 傳回值 pac
Math類
java.lang.Math提供了一系列靜態方法用於科學計算, 其方法的參數和傳回值類型一般都為double型, 如果需要更加強大的數學運算能力計算高等數學中的相關內容, 可使用apache commons下面的Math類庫
Math類的常用方法:
abs取絕對值
acos, asin, atan, cos, sin, tan三角函數
sqrt平方根
pow(double a, double b), a^b
max(double a, double b), 取最大值
min(double a, double b), 取最小值
ceil(double a), 大於a的最小整數
floor(double a), 小於a的最大整數
random(), 返回0.0到1.0的隨機數
long round(double a), double型資料a轉換為long型(四捨五入)
toDegrees(double angrad), 弧度轉換為角度
roRadians(double angdeg), 角度轉換為弧度
/**************樣本程式****************/public static void main(String[] args) { // 取正相關操作 System.out.println(Math.ceil(3.1)); System.out.println(Math.floor(3.4)); System.out.println(Math.round(3.1)); System.out.println(Math.round(3.8)); System.out.println("##########################"); // 絕對值, 開方, a的b次冪相關操作 System.out.println(Math.abs(-1)); System.out.println(Math.abs(-1.1)); System.out.println(Math.sqrt(36)); System.out.println(Math.pow(2, 4)); System.out.println("##########################"); // Math類中常用的常量 System.out.println(Math.PI); System.out.println(Math.E); System.out.println("##########################"); // 隨機數 System.out.println(Math.random());}/*4.03.034##########################11.16.016.0##########################3.1415926535897932.718281828459045##########################0.02732034556476759*/
Random類
Math類中雖然有產生隨機數的方法Math.random(), 但是通常需要的隨機數的範圍並不是[0,1)之間的double類型資料, 這時就需要對其進行一些複雜的運算. 如果使用Math.random()計算過於複雜的話, 可以使用另一種方式得到隨機數, 即Random類, 這個類是專門用來產生隨機數, 並且Math.random()底層就是調用的Random類的nextDouble()方法
/******************樣本程式*************************/import java.util.Random;public static void main(String[] args) { Random rand = new Random(); // 隨機產生[0,1)之間的double類型的資料 System.out.println(rand.nextDouble()); System.out.println("#########################"); // 隨機產生int類型允許範圍之內的整型資料 System.out.println(rand.nextInt()); System.out.println("#########################"); // 隨機產生[0,1)之間的float類型資料 System.out.println(rand.nextFloat()); System.out.println("#########################"); // 隨機產生false或true System.out.println(rand.nextBoolean()); System.out.println("#########################"); // 隨機產生[0,10)之間的int類型的資料 System.out.println(rand.nextInt(10)); System.out.println("#########################"); // 隨機產生[20,30)之間的int類型的資料 System.out.println(rand.nextInt(10) + 20); System.out.println("#########################"); // 隨機產生[20,30)之間的int類型的資料(此種方法計算較為複雜) System.out.println((int)(rand.nextDouble() * 10) + 20); System.out.println("#########################");}/*0.18579466820637747#########################1695590674#########################0.8908015#########################false#########################9#########################21#########################25#########################*/
Math類和Random類