Java - StrictMath abs(int) 方法



描述

Java StrictMath abs(int a) 方法返回 int 值的絕對值。如果引數非負,則返回該引數。如果引數為負,則返回該引數的負值。請注意,如果引數等於 Integer.MIN_VALUE 的值(可表示的最小 int 值),則結果為該值本身,它是負數。

宣告

以下是 java.lang.StrictMath.abs() 方法的宣告

public static int abs(int a)

引數

a − 需要確定絕對值的引數

返回值

此方法返回引數的絕對值。

異常

獲取正整數的絕對值示例

以下示例演示瞭如何使用 StrictMath abs() 方法獲取正整數的絕對值。

package com.tutorialspoint;

public class StrictMathDemo {

   public static void main(String[] args) {

      // get a int to find its absolute values
      int x = 4876;
   
      // get and print its absolute value
      System.out.println("StrictMath.abs(" + x + ")=" + StrictMath.abs(x));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

StrictMath.abs(4876)=4876

獲取零整數的絕對值示例

以下示例演示瞭如何使用 StrictMath abs() 方法獲取零整數的絕對值。

package com.tutorialspoint;

public class StrictMathDemo {

   public static void main(String[] args) {

      // get a int to find its absolute values
      int x = -0;
   
      // get and print its absolute value
      System.out.println("StrictMath.abs(" + x + ")=" + StrictMath.abs(x));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

StrictMath.abs(0)=0

獲取負整數的絕對值示例

以下示例演示瞭如何使用 StrictMath abs() 方法獲取負整數的絕對值。

package com.tutorialspoint;

public class StrictMathDemo {

   public static void main(String[] args) {

      // get a int to find its absolute values
      int x = -9999;
   
      // get and print its absolute value
      System.out.println("StrictMath.abs(" + x + ")=" + StrictMath.abs(x));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

StrictMath.abs(-9999)=9999
java_lang_strictmath.htm
廣告