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()
方法接受一个参数。int
double
浮动
长
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()
方法将负值转换为正值。