当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Integer signum()用法及代码示例


符号函数是一个奇数数学函数,可提取实数的符号。符号函数也称为符号函数。
java.lang的Integer.signum()方法返回指定整数值的正负号函数。对于正值,负值和零,该方法分别返回1,-1和0。

用法:

public static int signum(int a)

参数:该方法采用整数类型的一个参数a,对其进行运算。


返回值:该方法返回指定整数值的符号函数。如果指定的值为负,则返回-1,如果指定的值为零,则返回0,如果指定的值为正,则返回1。

例子:

Consider an integer a = 27
Since 27 is a positive int signum will return= 1
        
Consider another integer a = -61
Since -61 is a negative int signum will return= -1
     
Consider the integer value a = 0
For a zero signum, it will return = 0 

以下示例程序旨在说明Java.lang.Integer.signum()方法:
示例1:

// Java program to illustrate the 
// Java.lang.Integer.signum() Method 
import java.lang.*; 
  
public class Geeks { 
  
public static void main(String[] args) { 
  
    // It will return 1 as  the int value is greater than 1 
    System.out.println(Integer.signum(1726)); 
  
    // It will return -1 as  the int value is less than 1 
    System.out.println(Integer.signum(-13)); 
  
    // It will returns 0 as int value is equal to 0 
    System.out.println(Integer.signum(0)); 
} 
} 
输出:
1
-1
0

示例2:

// Java program to illustrate the 
// Java.lang.Integer.signum() Method 
import java.lang.*; 
  
public class Geeks { 
  
public static void main(String[] args) { 
  
    // It will return 1 as  the int value is greater than 1 
    System.out.println(Integer.signum(-1726)); 
  
    // It will return -1 as  the int value is less than 1 
    System.out.println(Integer.signum(13)); 
  
    // It will returns 0 as int value is equal to 0 
    System.out.println(Integer.signum(0)); 
} 
} 
输出:
-1
1
0

示例3:用于十进制值和字符串。
注意:当将十进制值和字符串作为参数传递时,它将返回错误消息。

// Java program to illustrate the 
// Java.lang.Integer.signum() Method 
import java.lang.*; 
  
public class Geeks { 
  
public static void main(String[] args) { 
  
    //retuns compile time error as passed argument is a decimal value 
    System.out.println(Integer.signum(3.81)); 
      
      
    //retuns compile time error as passed argument is a string  
    System.out.println(Integer.signum("77")); 
  
  
} 
} 
输出:
prog.java:10: error: incompatible types: possible lossy conversion from double to int
    System.out.println(Integer.signum(3.81));
                                      ^
prog.java:14: error: incompatible types: String cannot be converted to int
    System.out.println(Integer.signum("77"));
                                      ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors


相关用法


注:本文由纯净天空筛选整理自ankita_chowrasia大神的英文原创作品 Integer signum() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。