Java Math abs()方法及实例
绝对值是指与参数中传递的数字相对应的正值。现在极客们一定想知道它到底是什么意思,所以它指的是不管是正数还是负数被传递给计算,在这两种情况下,计算都会发生在对应的正数上。 所以为了计算任何数字的绝对值,我们在Java中有一个指定的方法,称为 abs() ,存在于java.lang包内的Math类中。
java.lang.Math.abs() 返回一个给定参数的绝对值。
如果参数不是负数,则返回该参数。如果参数是负数,则返回该参数的负数。语法:
public static DataType abs(DataType a)
参数: 要确定其绝对值的Int、long、float或double值。
返回类型: 该方法返回参数的绝对值。
抛出的异常: ArithmeticException
提示: 必须注意以下的通用返回类型。
如果参数是double或float类型。如果参数是正零或负零,结果是正零。如果参数是无穷大,结果是正无穷大。如果参数是NaN,结果是NaN。如果参数是int或long类型: 如果参数等于Integer.MIN_VALUE或Long.MIN_VALUE的值,即最负的可表示的int或long的值,结果是相同的值,即为负值。例1 :
// Java Program to Illustrate Absolute Method// of Math Class // Importing all Math classes// from java.lang packageimport java.lang.Math; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom integer input received from user int n = -7; // Printing value before applying absolute function System.out.println( "Without applying Math.abs() method : " + n); // Applying absolute math function and // storing it in integer variable int value = Math.abs(n); // Printing value after applying absolute function System.out.println( "With applying Math.abs() method : " + value); }}输出
Without applying Math.abs() method : -7With applying Math.abs() method : 7
例2 :
// Java Program to Demonstrate Working of abs() method// of Math class inside java.lang package // Importing Math class// from java.lang packageimport java.lang.Math; // Main classclass GFG { // Main driver method public static void main(String args[]) { // Customly declaring and initializing all // arguments that ans() function takes // Float float a = 123.0f; float b = -34.2323f; // Double double c = -0.0; double d = -999.3456; // Integer int e = -123; int f = -0; // Long long g = -12345678; long h = 98765433; // abs() method taking float type as input System.out.println(Math.abs(a)); System.out.println(Math.abs(b)); // abs() method taking double type as input System.out.println(Math.abs(1.0 / 0)); System.out.println(Math.abs(c)); System.out.println(Math.abs(d)); // abs() method taking int type as input System.out.println(Math.abs(e)); System.out.println(Math.abs(f)); System.out.println(Math.abs(Integer.MIN_VALUE)); // abs() method taking long type as input System.out.println(Math.abs(g)); System.out.println(Math.abs(h)); System.out.println(Math.abs(Long.MIN_VALUE)); }}输出
123.034.2323Infinity0.0999.34561230-21474836481234567898765433-9223372036854775808
