Java Math negateExact() 方法
示例
改變不同數字的符號
System.out.println(Math.negateExact(15));
System.out.println(Math.negateExact(-32));
System.out.println(Math.negateExact(7));
System.out.println(Math.negateExact(-25));
自己動手試一試 »
定義和用法
negateExact()
方法返回一個值與另一個整數相等但符號相反的整數,如果發生溢位則丟擲異常。這可以防止因溢位而導致的錯誤結果。
當整數等於 Integer.MIN_VALUE
或 Long.MIN_VALUE
(最大的負整數)時,會發生溢位,因為它們沒有對應的正整數。
語法
以下之一
public static int negateExact(int x)
public static long negateExact(long x)
引數值
引數 | 描述 |
---|---|
x | 必需。要取反的整數。 |
技術詳情
返回 | 一個 int 或 long 值,表示一個與另一個整數值相等但符號相反的整數。 |
---|---|
丟擲 | ArithmeticException - 如果取反導致溢位。 |
Java 版本 | 1.8+ |
❮ Math 方法