欢迎访问宙启技术站
智能推送

Java函数:求绝对值

发布时间:2023-07-06 04:18:47

绝对值是指一个数离0点的距离。在Java中,求一个数的绝对值可以使用对应的数学库函数或者自定义函数来实现。下面分别介绍两种方法。

方法一:使用Math类的abs()函数

Java的Math类中有一个abs()函数,用于求绝对值。它的使用方式是 Math.abs(数字)。例如,要求-5的绝对值,可以使用Math.abs(-5)。下面是一个示例代码:

public class AbsoluteValue {
  public static void main(String[] args) {
    int num = -5;
    int absValue = Math.abs(num);
    System.out.println("The absolute value of " + num + " is " + absValue);
  }
}

输出:

The absolute value of -5 is 5

方法二:自定义函数

如果不想使用Math类的abs()函数,也可以自己定义一个函数来求绝对值。下面是一个示例代码:

public class AbsoluteValue {
  public static void main(String[] args) {
    int num = -5;
    int absValue = abs(num);
    System.out.println("The absolute value of " + num + " is " + absValue);
  }
  
  public static int abs(int num) {
    if (num < 0) {
      return -num;
    } else {
      return num;
    }
  }
}

输出:

The absolute value of -5 is 5

以上就是求绝对值的两种方法。无论使用哪种方式,最终都可以得到输入数字的绝对值。