在Java中,要求一個(gè)數(shù)的絕對(duì)值,可以使用Math.abs()
方法。這個(gè)方法接受一個(gè)double
類型的參數(shù),并返回其絕對(duì)值。以下是一些示例:
public class AbsoluteValue {
public static void main(String[] args) {
int number1 = -5;
int number2 = 7;
double number3 = -3.5;
double number4 = 4.2;
System.out.println("絕對(duì)值 of " + number1 + " is: " + Math.abs(number1)); // 輸出: 5
System.out.println("絕對(duì)值 of " + number2 + " is: " + Math.abs(number2)); // 輸出: 7
System.out.println("絕對(duì)值 of " + number3 + " is: " + Math.abs(number3)); // 輸出: 3.5
System.out.println("絕對(duì)值 of " + number4 + " is: " + Math.abs(number4)); // 輸出: 4.2
}
}
注意:Math.abs()
方法對(duì)于整數(shù)類型(如int
、long
)只能求正數(shù)的絕對(duì)值,對(duì)于負(fù)數(shù)會(huì)返回相反數(shù)。對(duì)于浮點(diǎn)數(shù)類型(如double
、float
),它會(huì)返回一個(gè)接近于零的數(shù),但不會(huì)改變其符號(hào)。