Getting started with JavaSE 31: Math class of common Java classes
This Math class is generally not used, but we still need to know about it for future use.
I. Data operations using Math
The Math class is located in the java. lang Package and contains methods used to execute basic mathematical operations. All methods of the Math class are static methods.
You can directly use the class name. method name, such as Math. round ();
Common Methods:
Follow the examples of the above four common methods:
Running result:
Let's look at an example:
Function: defines an integer array containing 10 elements. A Random Number of less than 10 is randomly generated, each element in the array is assigned a value, and the output is
Result. The Code is as follows:
Public class Test {public static void main (String [] args) {// defines an integer array with a length of 10int [] nums = new int [10]; // assign the value for (int I = 0; I <nums. length; I ++) {// generate a random number less than 10 int x = (int) (Math. random () * 10); // assign nums [I] = x to the element;} // use the foreach loop to output the element for (int num: nums) {ystem. out. println (num + "");}}}
Running result:
Math fields and method (1) fields
The following are fields of the java. lang. Math class:
(2) class methods
(3) inherited methods
This class inherits the method from the following class: java. lang. Object
Refer to my previous blog JavaSE getting started 24: Object class details in Java object-oriented supplements.
Three simple instances
Instance code:
public class Test{ public static void main(String args[]){double a = Math.round(Math.random()*10);double b = Math.round(Math.random()*10);System.out.println(Math.sqrt(a*a+b*b));System.out.println(Math.pow(a,8));System.out.println(Math.round(b));System.out.println(Math.log(Math.pow(Math.E,15)));double d = 60.0;double r = Math.PI/4;System.out.println(Math.toRadians(d));System.out.println(Math.toDegrees(r)); }}
Running result: