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); } }
新聞熱點
疑難解答