Java Math incrementExact(int x) 方法


我們將透過在 Java 中使用該函式並瞭解其不同的功能來探索 Java Math incrementExact(int x) 方法。

incrementExact() 函式是 Java 中 Math 庫的內建函式。此函式用於返回一個值,該值等於函式中傳入的引數加 1。如果函式中作為引數傳入的整數值溢位,則該函式會丟擲異常,溢位取決於函式中傳入的資料型別,即 int 或 long。

語法

函式的語法 -

int a;
int incrementExact(a);

long a;
long incrementExact(a);

函式中傳入的引數只是一個整數值,如上所述,可以是 int 或 long 資料型別。返回值等於函式中傳入的引數加 1。如果函式中傳入的引數值溢位給定資料型別,則該函式會丟擲異常。

在本文中,我們將討論 incrementExact() 函式在 Java 中的實現及其工作原理。我們將編寫一段 Java 程式碼,其中我們將獲得一個數字作為輸入,我們需要使用 incrementExact() 函式列印等於輸入值加 1 的值。

讓我們透過以下示例來了解問題。

INPUT : x=6
OUTPUT : 7

說明 - 在這裡,我們得到一個等於 6 的整數。我們需要使用 incrementExact() 輸出列印等於給定整數加 1 的值。因此,輸出將為 7。

INPUT : x= -10
OUTPUT : -9

說明 - 給定的整數值為 -10。使用 incrementExact() 函式,將 x 作為引數傳入函式,我們將得到等於 x 加 1 的值,該值將等於 -9,這是所需的輸出。

讓我們在 Java 程式碼中實現 incrementExact() 函式,以瞭解如何實現該函式及其工作原理。

Java 程式以檢視 incrementExact() 函式的功能

在程式碼中實現該函式需要遵循以下步驟。

  • 使用 java.lang.Math 匯入 java 數學庫。

  • 初始化一個變數以儲存程式碼中的輸入。

  • 然後,我們將再次建立一個變數來儲存 incrementExact() 函式的輸出,其中傳入的引數將是輸入變數。

  • 返回我們儲存函式返回值的變數,該返回值將等於輸入變數的值加 1,即我們所需的輸出。

示例

函式實現的 Java 程式碼 -

//Java Code to see the implementation of the incrementExact() function
import java.lang.Math; //to import the math library

public class Main {
   public static  void main(String [] args) { 
      //to store the input value
      long x;
      x=1578;
        
      //to store the value returned by the incrementExact() function
      long ans;
      ans=Math.incrementExact(x); //passing the parameter as input value
       
      //printing the output of the function
      System.out.println("The output after the implementation of the function : "+ans);
   }
}

輸出

The output after the implementation of the function : 1579  

時間複雜度 - O(1),因為執行函式中的操作需要常數時間。

空間複雜度 - O(1),因為不需要額外的空間。

Java 程式以檢視函式輸出何時溢位

實現 incrementExact() 函式的步驟如下。

  • 使用 java.lang.Math 在 Java 中匯入數學庫。

  • 將輸入值儲存在一個變數中,作為整數的最大值,以檢視函式中值的溢位情況。

  • 將函式 incrementExact() 的輸出儲存在一個變數中,其中函式中的傳入引數是輸入值。

  • 由於函式中傳入的引數是整數的最大值,當加 1 時會顯示值溢位,因此程式碼將顯示整數溢位異常。

示例

檢視整數溢位的 Java 程式碼

//Java Code to see the implementation of the incrementExact() function
import java.lang.Math; //to import the math library

public class Main {
   public static  void main(String [] args) { 
      //to store the input value
      long x;
      x=Long.MAX_VALUE;
        
      //to store the value returned by the incrementExact() function
      long ans;
      ans=Math.incrementExact(x); //passing the parameter as input value
        
      //printing the output of the function
      System.out.println(ans);
   }
}

輸出

Exception in thread "main" java.lang.ArithmeticException: integer overflow
   at java.base/java.lang.Math.incrementExact(Math.java:964)
   at Main.main(Main.java:14)

更新於: 2023年4月18日

138 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.