为了更好地理解这个示例,我们始终建议您学习下面列出的 Golang 编程 的基础主题
交换两个数字意味着交换两个变量的值。
例如,我们有两个变量 v1 和 v2。v1 的值是 10,v2 的值是 20。交换后,v1 的值将变为 20,v2 的值将变为 10。
这里我们展示了如何在 Go 语言中交换两个数字。这里变量 x, y 保存着要交换的数字,另一个变量 temp 用于帮助交换。首先,将第一个变量 x 移动到 temp 变量,然后将第二个变量 y 移动到第一个变量 x。最后,将 temp 变量移动到第二个变量 y。下面是在 Go 程序中使用的步骤。
第一步:导入 fmt 包
第二步:启动 main() 函数
步骤 3:声明变量 x, y, temp
步骤 4:使用 fmt.Scanfln() 读取第一个数字 x
步骤 5:使用 fmt.Scanfln() 读取第二个数字 y
步骤 6:将 x 移动到 temp,即 temp=x
步骤 7:将 y 移动到 x,即 x=y
步骤 8:将 temp 移动到 y,即 y=temp
步骤 9:最后使用 fmt.Println() 打印 x, y
package main
import "fmt"
func main() {
var x, y, temp int
fmt.Print("Enter the first number x = ")
fmt.Scanln(&x)
fmt.Print("Enter the second number y = ")
fmt.Scanln(&y)
temp = x
x = y
y = temp
fmt.Println("The first number after swap = ", x)
fmt.Println("The second number after swap = ", y)
}
Enter the first number x = 13 Enter the second number y = 28 The first number after swap = 28 The second number after swap = 13