在 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