跳到主要内容

Java Math abs() 方法

abs() 方法返回指定值的绝对值。

示例

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

// 打印绝对值
System.out.println(Math.abs(-7.89));

}
}

Math.abs() 方法的语法

abs() 方法的语法是:

Math.abs(num)

这里,abs() 是一个静态方法。因此,我们使用类名 Math 来访问该方法。

abs() 方法的参数

abs() 方法接受单个参数。

  • num - 要返回其绝对值的数字。数字可以是:
    • int
    • double
    • float
    • long

abs() 方法的返回值

  • 返回指定数字的绝对值
  • 如果指定数字为负数,则返回其正值

示例 1:Java Math abs() 与正数

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

// 创建变量
int a = 7;
long b = -23333343;
double c = 9.6777777;
float d = -9.9f;

// 打印绝对值
System.out.println(Math.abs(a)); // 7
System.out.println(Math.abs(c)); // 9.6777777

// 打印去掉负号的值
System.out.println(Math.abs(b)); // 23333343
System.out.println(Math.abs(d)); // 9.9
}
}

在上述示例中,我们导入了 java.lang.Math 包。如果我们想使用 Math 类的方法,这是很重要的。注意这个表达式,

Math.abs(a)

这里,我们直接使用类名来调用方法。这是因为 abs() 是一个静态方法。

示例 2:Java Math abs() 与负数

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

// 创建变量
int a = -35;
long b = -141224423L;
double c = -9.6777777d;
float d = -7.7f;

// 获取绝对值
System.out.println(Math.abs(a)); // 35
System.out.println(Math.abs(b)); // 141224423
System.out.println(Math.abs(c)); // 9.6777777
System.out.println(Math.abs(d)); // 7.7
}
}

这里,我们可以看到 abs() 方法将负值转换为正值。