Java Math negateExact() 方法

定义和用法

negateExact() 方法返回与另一个整数等值但符号相反的整数,并在发生溢出时抛出异常。这可以防止因溢出而导致的不正确结果。

当整数等于 Integer.MIN_VALUELong.MIN_VALUE(即最大的负整数)时,会发生溢出,因为它没有对应的正等值。

实例

改变不同数字的符号:

System.out.println(Math.negateExact(15));
System.out.println(Math.negateExact(-32));
System.out.println(Math.negateExact(7));
System.out.println(Math.negateExact(-25));

亲自试一试

语法

以下之一:

public static int negateExact(int x)
public static long negateExact(long x)

参数

参数 描述
x 必需。要取反的整数。

技术细节

返回: 表示与另一个整数等值但符号相反的 intlong 值。
抛出: ArithmeticException - 如果取反导致溢出。
Java 版本: 1.8+