Java教程

Java Math abs()

Java Math abs()

在本教程中,我们将通过示例了解 Java Math.abs() 方法。
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 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() 方法将负值转换为正值。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4