當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。