java.lang.Math.abs()返回给定参数的绝对值。
如果参数不为负,则返回参数。
如果参数为负,则返回参数的取反。
用法:
public static DataType abs(DataType a)
a:the argument whose absolute value is to be determined
返回: This method returns the absolute value of the argument.
如果参数为double或float类型:
如果参数为正零或负零,则结果为正零。
如果参数为无穷大,则结果为正无穷大。
如果参数为NaN,则结果为NaN。
如果参数为int或long类型:
如果参数等于Integer.MIN_VALUE或Long.MIN_VALUE的值,则最负
可表示的int或long值,结果是相同的值,为负。
// Java program to demonstrate working
// of java.lang.Math.abs() method
import java.lang.Math;
class Gfg {
// driver code
public static void main(String args[])
{
float a = 123.0f;
float b = -34.2323f;
double c = -0.0;
double d = -999.3456;
int e = -123;
int f = -0;
long g = -12345678;
long h = 98765433;
// abs() method taking float type as input
System.out.println(Math.abs(a));
System.out.println(Math.abs(b));
// abs() method taking double type as input
System.out.println(Math.abs(1.0 / 0));
System.out.println(Math.abs(c));
System.out.println(Math.abs(d));
// abs() method taking int type as input
System.out.println(Math.abs(e));
System.out.println(Math.abs(f));
System.out.println(Math.abs(Integer.MIN_VALUE));
// abs() method taking long type as input
System.out.println(Math.abs(g));
System.out.println(Math.abs(h));
System.out.println(Math.abs(Long.MIN_VALUE));
}
}
输出:
123.0
34.2323
Infinity
0.0
999.3456
123
0
-2147483648
12345678
98765433
-9223372036854775808