abs()
方法返回指定值的绝对值。
示例
class Main {
public static void main(String[] args) {
// print the absolute value
System.out.println(Math.abs(-7.89));
}
}
Math.abs() 的语法
abs()
方法的语法是
Math.abs(num)
这里,abs()
是一个静态方法。因此,我们使用类名 Math
来访问该方法。
abs() 参数
abs()
方法接受一个参数。
- num - 要返回其绝对值的数字。该数字可以是
int
双精度浮点数
浮点数
long
注意: 要了解有关 int
、double
、float
和 long
的更多信息,请访问 Java 数据类型(原始类型)。
abs() 返回值
- 返回指定数字的绝对值
- 如果指定数字为负数,则返回正值
示例 1:Java Math abs() 与正数
class Main {
public static void main(String[] args) {
// create variables
int a = 7;
long b = -23333343;
double c = 9.6777777;
float d = -9.9f;
// print the absolute value
System.out.println(Math.abs(a)); // 7
System.out.println(Math.abs(c)); // 9.6777777
// print the value without negative sign
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) {
// create variables
int a = -35;
long b = -141224423L;
double c = -9.6777777d;
float d = -7.7f;
// get the absolute value
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()
方法将负值转换为正值。