Go語言程式:提取給定年份的後兩位數字


本教程將討論如何編寫一個Go程式來提取給定年份的後兩位數字。

此程式以任何年份作為輸入,並列印其後兩位數字。您需要使用取模運算子來提取給定年份的後兩位數字。

取模運算

% 運算子是取模運算子,它返回除法後的餘數而不是商。這對於查詢相同數字的倍數很有用。顧名思義,在需要處理數字位數的運算中,取模運算子起著至關重要的作用。這裡的目標是提取數字的最後幾位。

為了提取最後兩位數字,需要將給定數字除以100。

在函式中提取給定年份的後兩位數字

語法

var variableName integer = var year int

我們使用算術運算子取模 % 來查詢最後兩位數字。

lasttwoDigits := year % 1e2

1e2 代表 1*100

演算法

步驟 1 − 匯入 fmt 包

步驟 2 − 開始 main() 函式

步驟 3 − 宣告變數 year

步驟 4 − 檢查條件為 year % 1e2 (1e2 是用科學計數法表示的數字,它表示 1 乘以 10 的 2 次冪 (e 是指數)。因此 1e2 等於 1*100)

步驟 5 − 根據上述條件,提取年份的後兩位數字

步驟 6 − 列印輸出。

示例

下面的程式程式碼顯示瞭如何在函式中提取任何給定年份的後兩位數字

package main // fmt package provides the function to print anything import "fmt" func main() { // define the variable var year int // initializing the variable year = 1897 fmt.Println("Program to extract the last two digits of a given year within the function.") // use modulus operator to extract last two digits // % modulo-divides two variables lasttwoDigits := year % 1e2 // 1e2 stands for 1*100 // printing the results fmt.Println("Year =", year) fmt.Println("Last 2 digits is : ", lasttwoDigits) }

輸出

Program to extract the last two digits of a given year within the function.
Year = 1897
Last 2 digits is :  97

程式碼描述

  • 在上面的程式中,我們聲明瞭 main 包。

  • 在這裡,我們匯入了 fmt 包,其中包含 fmt 包的檔案,然後我們可以使用與 fmt 包相關的函式。

  • 在 main() 函式中,我們宣告並初始化一個變數整數 var year int

  • 接下來,我們使用取模運算子來提取給定年份的後兩位數字

  • 使用 fmt.Println 在控制檯螢幕上列印年份的後兩位數字。

在兩個單獨的函式中提取任何給定年份的後兩位數字

語法

func d(year int) (lastTwo int)

我們使用算術運算子取模 % 來查詢最後兩位數字。

演算法

步驟 1 − 匯入 fmt 包

步驟 2 − 初始化變數。

步驟 3 − 使用 year % 100 提取最後兩位數字

步驟 4 − 列印結果

示例

package main // fmt package provides the function to print anything import "fmt" // This function to extract the last two digits of a given year in the function parameter func d(year int) (lastTwo int) { // use modulus operator to extract last two digits fmt.Println("The Year = ", year) lastTwo = year % 100 return } func main() { // define the variable var year, lastTwo int // initializing the variables year = 2013 fmt.Println("Program to extract the last two digits of a given year in 2 separate functions.") lastTwo = d(year) // printing the results fmt.Println("Last 2 digits is : ", lastTwo) }

輸出

Program to extract the last two digits of a given year in 2 separate functions.
The Year =  2013
Last 2 digits is :  13

程式碼描述

  • 首先,我們匯入 fmt 包

  • 然後我們建立 func d() 函式來提取給定年份的後兩位數字

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

  • var year, lastTwo int − 在這行程式碼中,我們宣告並初始化了整數

  • 然後我們呼叫在函式外部建立的 d() 函式,並將結果儲存在第二個整數變數 lastTwo 中

  • 最後使用 fmt.Println 在控制檯螢幕上列印給定年份的後兩位數字。

結論

使用上述程式碼,我們可以成功地使用 Go 語言程式提取任何給定年份的後兩位數字。

更新於:2022年11月30日

瀏覽量:1K+

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告