CodeGym/Java 博客/随机的/Java 数学 abs() 方法
John Squirrels

San Francisco

# Java 数学 abs() 方法

## Java 中的 Math.abs() method() 是什么？

java.lang.Math类提供了一个静态方法Math.abs(parameter)来求参数的绝对值”。

## 方法头

``public static dataType abs(dataType parameter)``

## 允许的数据类型

Java 的abs ()方法针对各种数据类型进行了重载。允许的类型如下。
int float double long

## 示例 1

``````public class DriverClass {
public static void main(String args[]) {

int number = +5;
// Print the original number
System.out.println("Original Number = " + number);

// Printing the absolute value
// Calling the Math.abs() method
System.out.println("Absolute Number = " + "Math.abs( " + number + " ) = " + Math.abs(number));

number = -5;
// Print the original number
System.out.println("Original Number = " + number);

// Printing the absolute value
// Calling the Math.abs() method
System.out.println("Absolute Number = " + "Math.abs( " + number + " ) = " + Math.abs(number));

}
}``````

## 示例 2

``````public class DriverClass {
public static void main(String args[]) {

int number = -0;
System.out.println("Original Number = " + number);
System.out.println("Math.abs( " + number + " ) = " + Math.abs(number) + "\n");

long number1 = -4499990;
System.out.println("Original Number = " + number1);
System.out.println("Math.abs( " + number1 + " ) = " + Math.abs(number1) + "\n");

float number2 = -92.45f;
System.out.println("Original Number = " + number2);
System.out.println("Math.abs( " + number2 + " ) = " + Math.abs(number2) + "\n");

double number3 = -63.7777777777;
System.out.println("Original Number = " + number3);
System.out.println("Math.abs( " + number3 + " ) = " + Math.abs(number3) + "\n");
}
}``````

## 边界情况

### 对于 int 和 long 数据类型

Math.abs(Integer.MIN_VALUE) = -2147483648 Math.abs(Long.MIN_VALUE) = -9223372036854775808

### 对于 float 和 double 数据类型

Math.abs(Double.NEGATIVE_INFINITY) = 无穷大

Math.abs(Double.NaN) = NaN