Java - Math abs(long) 方法



描述

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

宣告

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

public static long abs(long a)

引數

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

返回值

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

異常

獲取正 long 值的絕對值示例

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

package com.tutorialspoint;

public class MathDemo {

   public static void main(String[] args) {

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

輸出

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

Math.abs(4876)=4876

獲取零 long 值的絕對值示例

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

package com.tutorialspoint;

public class MathDemo {

   public static void main(String[] args) {

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

輸出

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

Math.abs(0)=0

獲取負 long 值的絕對值示例

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

package com.tutorialspoint;

public class MathDemo {

   public static void main(String[] args) {

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

輸出

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

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