在 Java 中獲取 float、int、double 和 long 的絕對值
java.lang.Math 類有一個 abs() 方法,它可以幫助我們找到不同資料型別的絕對值。
float 的絕對值
為了計算 float 值的絕對值,我們使用 java.lang.Math.abs(float a) 方法。如果引數 'a' 為負數,則返回 'a' 的相反數。如果引數 'a' 為非負數,則返回引數本身。當引數為正零或負零時,結果為正零。如果引數為無限大,則結果為正無限大。如果引數為 NaN,則結果為 NaN。
宣告 - Math.abs(float a) 函式的宣告如下:
public static float abs(float a)
其中 a 是要返回其絕對值的引數。
int 的絕對值
為了計算 int 值的絕對值,我們使用 java.lang.Math.abs(int a) 方法。如果引數 'a' 為負數,則返回 'a' 的相反數。如果引數 'a' 為非負數,則返回引數本身。如果引數 'a' 的值為 Integer.MIN_VALUE,則返回負值本身。當引數為正零或負零時,結果為正零。
宣告 - Math.abs(int a) 函式的宣告如下:
public static int abs(int a)
其中 a 是要返回其絕對值的引數。
double 的絕對值
為了計算 double 值的絕對值,我們必須使用 java.lang.Math.abs(double a) 方法。如果引數 'a' 為負數,則返回 'a' 的相反數。如果引數 'a' 為非負數,則返回引數本身。當引數為正零或負零時,結果為正零。如果引數為無限大,則結果為正無限大。如果引數為 NaN,則結果為 NaN。
宣告 - Math.abs(double a) 函式的宣告如下:
public static double abs(double a)
其中 a 是要返回其絕對值的引數。
long 的絕對值
為了計算 long 值的絕對值,我們使用 java.lang.Math.abs(long a) 方法。如果引數 'a' 為負數,則返回 'a' 的相反數。如果引數 'a' 為非負數,則返回引數本身。如果引數 'a' 的值為 Long.MIN_VALUE,則返回負值本身。當引數為正零或負零時,結果為正零。
宣告 - Math.abs(long a) 函式的宣告如下:
public static long abs(long a)
其中 a 是要返回其絕對值的引數。
讓我們來看一個程式,在這個程式中我們找到 float、int、double 和 long 資料型別的絕對值。
示例
import java.lang.Math;
public class Example {
public static void main(String[] args) {
// declaring and initialising some integer values
int a = 10;
int b = -9;
// declaring and initialising some float values
float c = 8.11f;
float d = -9.32f;
// declaring and initialising some double values
double x = -100.01d;
double y = 90.344d;
// declaring and initialising some long values
long r = 1234567891223l;
long s = -4567891234554l;
//printing their absolute values
System.out.println("Absolute value of " + a + " = " + Math.abs(a));
System.out.println("Absolute value of " + b + " = " + Math.abs(b));
System.out.println("Absolute value of " + c + " = " + Math.abs(c));
System.out.println("Absolute value of " + d + " = " + Math.abs(d));
System.out.println("Absolute value of " + x + " = " + Math.abs(x));
System.out.println("Absolute value of " + y + " = " + Math.abs(y));
System.out.println("Absolute value of " + r + " = " + Math.abs(r));
System.out.println("Absolute value of " + s + " = " + Math.abs(s));
}
}輸出
Absolute value of 10 = 10 Absolute value of -9 = 9 Absolute value of 8.11 = 8.11 Absolute value of -9.32 = 9.32 Absolute value of -100.01 = 100.01 Absolute value of 90.344 = 90.344 Absolute value of 1234567891223 = 1234567891223 Absolute value of -4567891234554 = 4567891234554
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP