Golang 从给定的年份中提取最后两位数字
在本教程中,我们将讨论如何编写一个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
代码描述
- 在上面的程序中,我们声明了package 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 包
-
然后我们创建一个函数 d() 来提取给定年份的最后两位数字
-
然后我们开始 main() 函数
-
var year, lastTwo int – 在这行代码中,我们声明并初始化整数
-
然后我们调用 d() 函数,该函数我们在函数外创建,并将其存储在第二个整数变量 lastTwo 中
-
最后,使用 fmt.Println 在控制台屏幕上打印给定年份的最后两位数字
结论
使用上述代码,我们可以成功使用 Go 语言程序提取任何给定年份的最后两位数字。