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
代码的描述
- 在上面的程序中,我们声明了包main。
-
在这里,我们导入了fmt包,该包包括fmt包的文件,然后我们可以使用与fmt包相关的函数。
-
在main()函数中,我们声明并初始化一个变量integer var year int
-
接下来我们使用模数运算符来提取给定年份的最后两位数字
-
使用fmt.Println在控制台屏幕上打印出年份的最后两位数字。
在两个独立的函数中提取任何给定年份的最后两位数字
语法
func d(year int) (lastTwo int)
我们使用算术运算符modulus %来寻找最后两位数字。
算法
第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语言程序成功地提取任何指定年份的最后两位数字。
极客教程