1. Exam Points
Methodsof theMath class:
- static int
abs(int x) : returns the absolute value of an int value.- static double
abs(double x) : returns the absolute value of a double value.- static double
pow(double base, double exponent) : returns the value of the first parameter raised to the power of the second parameter.- static double
sqrt(double x) : returns the nonnegative square root of a double value.- static double
random() : returns a double value greater than or equal to 0.0 and less than 1.0 (0.0 ≤ x < 1.0).Generate double or int random values using the Math.random() method.
2. Knowledge Points
(1) Math Class
- The
Math classis part of the java.lang package. - Classes in the java.lang package are available by default.
- The
Math classcontainsonly class methods. Methods in the Math class:- static int
abs(int x) : returns the absolute value of an int value. - static double
abs(double x) : returns the absolute value of a double value. - static double
pow(double base, double exponent) : returns the value of the first parameter raised to the power of the second parameter. - static double
sqrt(double x) : returns the nonnegative square root of a double value. - static double
random() : returns a double value greater than or equal to 0.0 and less than 1.0 (0.0 ≤ x < 1.0).
- static int
- Example:
// 1. int Math.abs(int x) and double Math.abs(double x) (绝对值) int result1 = Math.abs(-10); // result1: 10 double result2 = Math.abs(-20.3); //result2: 20.3 // 2. double Math.pow(double x, double y) x^y (x的y次方) double result3 = Math.pow(3.0, 4.0); //result3: 3 to the power of 4 // 3. double Math.sqrt(double x): get the square root of x double result4 = Math.sqrt(16.0); // result4: 4.0 // 4. double Math.random() (生成随机数) // 0.0 <= x < 1.0, generate a double value between [0,1) double result5 = Math.random(); // 0.0 <= result5 < 1.0 // generate a double value between [0,10) double result6 = Math.random() * 10; // 0.0 <= result6 < 10.0 // generate an integer value between [0,10) int result7 = (int) (Math.random() * 10); // 0 <= result7 <= 9 // generate an integer value between [1,10] int result8 = (int) (Math.random() * 10) + 1; // 1 <= result8 <= 10 // generate an integer value between [m,n] (m <= x <= n) int m = 3; int n = 15; int result9 = (int) (Math.random() * (n - m + 1)) + m; - The values returned from
Math.random()can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range based on specified criteria. Example: