Golang 获得整数后继
在本文中,我们将讨论如何使用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包。
-
然后创建和定义了后继函数,该函数将返回用户输入的整数数值的下一个值。
-
然后我们开始了main()函数。
-
声明整数变量number和next。将number变量初始化为需要找到后继数的值。
-
调用上面创建的successor()函数,并传递number变量的值,并将结果存储在整数变量next中。
-
最后,使用fmt.Println()函数将整数的后继结果打印到屏幕上。
结论
我们已经成功编译并执行了Go语言程序,使用库函数在三个不同的示例中找到了整数的后继数。