下面的代码向您展示如何使用Math.signum()静态方法调用获取数字的符号函数。此方法提取实数的符号。如果你有许多x的符号函数x是-1如果x < 0; 0如果x = 0和1如果x > 0。
package org.nhooo.example.math; public class SignumExample { public static void main(String[] args) { Double zero = 0.0D; Double negative = -25.0D; Double positive = 15.0D; // 获取数字值的符号函数。 // 它返回: // * 0(如果值为零)。 // * 1.0(如果值大于零)。 // * -1.0,如果值小于零。 double sign1 = Math.signum(zero); double sign2 = Math.signum(negative); double sign3 = Math.signum(positive); // 对于浮点值 float sign4 = Math.signum(zero.floatValue()); float sign5 = Math.signum(negative.floatValue()); float sign6 = Math.signum(positive.floatValue()); System.out.println("In double:"); System.out.println("Signum of " + zero + " is " + sign1); System.out.println("Signum of " + negative + " is " + sign2); System.out.println("Signum of " + positive + " is " + sign3); System.out.println("In float:"); System.out.println("Signum of " + zero + " is " + sign4); System.out.println("Signum of " + negative + " is " + sign5); System.out.println("Signum of " + positive + " is " + sign6); } }
这是程序的输出:
In double: Signum of 0.0 is 0.0 Signum of -25.0 is -1.0 Signum of 15.0 is 1.0 In float: Signum of 0.0 is 0.0 Signum of -25.0 is -1.0 Signum of 15.0 is 1.0