Java signum 函数是 Math 库函数之一,用于查找给定表达式的符号,即正、负或零。在本文中,我们将通过一个示例展示如何在该编程语言中使用 Math.signum 函数。
Java signum 语法
该编程语言中 Math.signum 函数的基本语法如下所示
Math.signum(data_type number);
- 如果数字参数是正零或负零,Math.signum 函数将返回零作为输出。
- 如果数字参数是负数,它将返回负一 (-1) 作为输出。
- 当数字参数是正数时,它将返回正一 (+1) 作为输出。
- 如果不是数字,它将返回 NaN。
Java 编程提供了两种不同的 Math.signum 函数来返回给定表达式的符号。下面的函数将接受一个正数或负数双精度值作为参数并返回结果。
static double signum(double number); //Return type is double // To use in program: Math.signum(double number);
下面的函数将接受正数或负数浮点值作为参数并返回该值的符号。
static float signum(float number); //Return Type is float // To use in program: Math.signum(float number);
Java signum 函数示例
Math.signum 函数返回指定表达式的符号。在此 Java 示例中,我们将为不同的数据类型检查它并显示输出。
package MathFunctions;
public class SIgnumMethod {
public static void main(String[] args) {
double a = 44.5222, b = -698.6674;
float c = 56.23f, d = - 80.90f;
System.out.println("\nSignum Function result of Zero: " + Math.signum(0));
System.out.println("\nSignum Function of result Positive Double Value: " + Math.signum(a));
System.out.println("Signum Function of result Negative Double Value: " + Math.signum(b));
System.out.println("\nSignum Function of result Positive Float Value: " + Math.signum(c));
System.out.println("Signum Function of result Negative Float Value: " + Math.signum(d));
double e = Math.signum(10.90 + 15.10 - 20.50 + 1.50);
System.out.println("\nSignum Function results = " + e);
}
}

首先,我们将此 Java 函数用于零。接下来,我们将 Math.signum 函数用于变量 a 和 b(它们属于 double 类型)。它将调用 double 类型(static double signum(double number))方法来返回符号值。
System.out.println("\nNextUp result of Positive Doubles: " + Math.nextUp(a));
System.out.println("NextUp result of Negative Double Values: " + Math.nextUp(b));
接下来,我们将 signum 数学函数用于变量 c 和 d(它们属于 float 类型)。下面的语句将调用 float 类型方法(static float signum(float number))来返回符号值。
System.out.println("\nSignum Function of result Positive Float Value: " + Math.signum(c));
System.out.println("Signum Function of result Negative Float Value: " + Math.signum(d));
最后,声明了 Double 类型的变量,然后我们直接对表达式使用了 Math.signum 函数。
double a = Math.signum(10.90 + 15.10 - 20.50 + 1.50);