Java - Math abs(int) 方法



描述

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

宣告

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

public static int abs(int a)

引數

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

返回值

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

異常

獲取正整數的絕對值示例

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

package com.tutorialspoint;

public class MathDemo {

   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("Math.abs(" + x + ")=" + Math.abs(x));
   }
}

輸出

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

Math.abs(4876)=4876

獲取零整數的絕對值示例

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

package com.tutorialspoint;

public class MathDemo {

   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("Math.abs(" + x + ")=" + Math.abs(x));
   }
}

輸出

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

Math.abs(0)=0

獲取負整數的絕對值示例

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

package com.tutorialspoint;

public class MathDemo {

   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("Math.abs(" + x + ")=" + Math.abs(x));
   }
}

輸出

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

Math.abs(-9999)=9999
java_lang_math.htm
廣告