Go語言程式:獲取整數的後繼數


本文將討論如何使用Go語言庫函式獲取整數的後繼數。

整數的後繼數定義為緊跟其後的數。例如,2的後繼數是2 + 1 = 3。同樣,-50的後繼數是-49,以此類推。

語法

Syntax for Println() = fmt.Println(...interface{})

示例1:我們將使用庫函式在一個函式中獲取整數的後繼數

演算法

  • 步驟1 − 匯入fmt包。

  • 步驟2 − 開始函式main()

  • 步驟3 − 初始化一個int型別的變數並存儲值。

  • 步驟4 − 實現查詢後繼數的邏輯。

  • 步驟5 − 在螢幕上列印結果。

示例

// fmt package allows us to print anything on the screen. package main import "fmt" // Start the main() function func main() { fmt.Println("Golang program to find the successor of an integer number using library function") // declaring the integer variables var number, successor int // initializing the number variable number = 49 // implementing the logic successor = number + 1 // print the result fmt.Println("successor of", number, "is ", successor) }

輸出

Golang program to find the successor of an integer number using library function
successor of 49 is 50

程式碼描述

  • 首先,我們匯入fmt包,該包允許我們列印任何內容。

  • 然後我們開始main()函式。

  • 之後,我們必須宣告兩個整數變數number和successor。

  • 將number變數初始化為需要查詢其後繼數的值。其結果將儲存在整數變數successor中。

  • 然後建立查詢下一個整數值的邏輯。

  • 使用fmt.Println()函式在螢幕上列印結果。

示例2:我們將使用庫函式在兩個帶有引數和返回值的獨立函式中獲取整數的後繼數

演算法

  • 步驟1 − 匯入fmt包。

  • 步驟2 − 建立並定義successor()函式。

  • 步驟3 − 開始函式main()

  • 步驟4 − 宣告並初始化整數變數。

  • 步驟5 − 呼叫函式successor()

  • 步驟6 − 最後在螢幕上列印結果。

示例

package main import "fmt" // create a function to find the successor of an integer func successor(number int) int { // declare the integer variable n := number + 1 return n } // calling the main() function func main() { fmt.Println("Golang program to find the successor of an integer number using library function") // declaring the integer variables // initializing the integer variable number := 66 // calling the function successor() next := successor(number) // print the result fmt.Println("successor of", number, "is ", next) }

輸出

Golang program to find the successor of an integer number using library function
successor of 66 is 67

程式碼描述

  • 首先,我們匯入了允許我們列印任何內容的fmt包。

  • 然後建立並定義successor函式,該函式將返回使用者輸入的整數的下一個值。

  • 然後我們啟動了main()函式。

  • 宣告整數變數number和next。將number變數初始化為需要查詢其後繼數的值。

  • 呼叫上面建立的successor()函式並傳遞number變數的值,並將結果儲存在整數變數next中。

  • 最後,使用fmt.Println()函式在螢幕上列印整數後繼的結果。

結論

我們已經成功編譯並執行了Go語言程式,使用庫函式在三個獨立的示例中找到了整數的後繼數。

更新於:2022年11月16日

瀏覽量:169

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告