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和succeror。
-
将变量number初始化为一个值,必须找到其继承者的号码。其结果将被存储在整数变量succeror中。
-
然后创建一个逻辑来寻找下一个整数值。
-
使用 fmt.Println() 函数在屏幕上打印结果。
例2:我们将使用库函数在两个独立的函数中获取整数的后继者,并带参数和返回
算法
-
第1步 – 导入软件包fmt。
-
第2步 – 创建并定义 successor() 函数。
-
第3步 – 启动函数 main()。
-
第4步 – 声明并初始化整数变量。
-
第5步–调用函数 succeror()。
-
第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语言程序,在三个不同的例子中使用库函数找到了一个整数的继承者。
极客教程