abs()方法语法:
public static float abs(float f); public static int abs(int i); public static long abs(long l); public static double abs(double d);
abs()方法在java.lang包中可用。
这些方法用于返回方法中给定参数的绝对值。
这些方法不会引发异常。
这些是静态方法,可以使用类名进行访问,如果尝试使用类对象访问这些方法,则不会出现任何错误。
参数:
int / long / float / double-表示要找到其绝对值的值。
返回值:
此方法的返回类型为int / long / float / double-返回给定值的绝对值。
注意:
如果我们传递一个正值,则返回相同的值。
如果我们传递一个负值,则返回没有符号的相同值。
如果传递零,则返回相同的值(零)。
如果我们通过NaN,则返回NaN。
示例
//Java程序演示示例
//abs()StrictMath类的方法
public class Abs {
public static void main(String[] args) {
//变量声明
double a = 123.121d;
double b = -123.121d;
int c = 123121;
int d = -123121;
long e = 123121l;
long f = -123121l;
float g = 123.121f;
float h = -123.121f;
//显示a,b的先前值
System.out.println("a: " + a);
System.out.println("b: " + b);
//显示c,d的先前值
System.out.println("c: " + c);
System.out.println("d: " + d);
//显示e,f的先前值
System.out.println("e: " + e);
System.out.println("f:" + f);
//显示g,h的先前值
System.out.println("g: " + g);
System.out.println("h: " + h);
System.out.println();
System.out.println("abs(double): ");
//通过使用abs(double d)方法,我们将计算
//方法中给定参数的绝对值
System.out.println("StrictMath.abs(a): " + StrictMath.abs(a));
System.out.println("StrictMath.abs(b): " + StrictMath.abs(b));
System.out.println();
System.out.println("abs(int): ");
//通过使用abs(int i)方法,我们将计算
//方法中给定参数的绝对值
System.out.println("StrictMath.abs(c): " + StrictMath.abs(c));
System.out.println("StrictMath.abs(d): " + StrictMath.abs(d));
System.out.println();
System.out.println("abs(long): ");
//通过使用abs(long l)方法,我们将计算
//方法中给定参数的绝对值
System.out.println("StrictMath.abs(e): " + StrictMath.abs(e));
System.out.println("StrictMath.abs(f): " + StrictMath.abs(f));
System.out.println();
System.out.println("abs(double): ");
//通过使用abs(double d)方法,我们将计算
//方法中给定参数的绝对值
System.out.println("StrictMath.abs(g): " + StrictMath.abs(g));
System.out.println("StrictMath.abs(h): " + StrictMath.abs(h));
}
}输出结果
a: 123.121 b: -123.121 c: 123121 d: -123121 e: 123121 f:-123121 g: 123.121 h: -123.121 abs(double): StrictMath.abs(a): 123.121 StrictMath.abs(b): 123.121 abs(int): StrictMath.abs(c): 123121 StrictMath.abs(d): 123121 abs(long): StrictMath.abs(e): 123121 StrictMath.abs(f): 123121 abs(double): StrictMath.abs(g): 123.121 StrictMath.abs(h): 123.121