Java Math abs()方法返回指定值的絕對值。
abs()方法的語法為:
Math.abs(num)
num - 要返回其絕對值的數(shù)字。該數(shù)字可以是:
int
double
float
long
返回指定數(shù)字的絕對值
如果指定的數(shù)字為負,則返回正值
注意: abs()方法是靜態(tài)方法。因此,我們可以使用類的名稱直接訪問該方法。也就是,Math.abs()。
import java.lang.Math; class Main { public static void main(String[] args) { // 創(chuàng)建變量 int a = 7; long b = 23333343; double c = 9.6777777; float d = 9.9f; //打印絕對值 System.out.println(Math.abs(a)); // 7 System.out.println(Math.abs(c)); // 9.6777777 //打印不帶負號的值 System.out.println(Math.abs(b)); // 23333343 System.out.println(Math.abs(d)); // 9.9 } }
在上面的示例中,我們已導(dǎo)入java.lang.Math包,如果我們要使用Math類的方法,這一點很重要。注意表達式
Math.abs(a)
在這里,我們直接使用了類名來調(diào)用方法。這是因為abs()是靜態(tài)方法。
import java.lang.Math; class Main { public static void main(String[] args) { //創(chuàng)建變量 int a = -35; long b = -141224423L; double c = -9.6777777d; float d = -7.7f; // 得到絕對值 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()方法將負值轉(zhuǎn)換為正值。