[java] 获取指定值的绝对值,math.abs()的方法使用
math.abs()方法传入类型为int,long,double,float四种类型,输出指定值的绝对值
一、代码示例
1.正值打印
代码如下(示例):
inta =18;
long b = 2222;
double c = 10.333;
float d = 10.33f;
//打印绝对值
System.out.println("a的值"+Math.abs(a));
System.out.println("b的值"+Math.abs(b));
System.out.println("c的值"+Math.abs(c));
System.out.println("d的值"+Math.abs(d));
输出:
a的值18
b的值2222
c的值10.333
d的值10.33
2.负值打印
代码如下(示例):
int a = -18;
long b = -2222;
double c = -10.333;
float d = -10.33f;
//打印绝对值
System.out.println("a的值"+Math.abs(a));
System.out.println("b的值"+Math.abs(b));
System.out.println("c的值"+Math.abs(c));
System.out.println("d的值"+Math.abs(d));
输出:
a的值18
b的值2222
c的值10.333
d的值10.33
总结
math.abs()方法传入类型为int,long,double,float四种类型,输入正值或者是负值,输出为该值的绝对值