编写一个 Go 语言程序来交换两个数字,而无需使用第三个变量


解决这个问题的方法

  • 步骤 1:定义一个接受两个数字并返回类型为 int 的函数。
  • 步骤 2:查找 b = a + b;
  • 步骤 3:然后 a = b – a,并且 b = b – a

程序

在线演示

package main
import "fmt"

func swap(a, b int){
   fmt.Printf("Before swapping, numbers are %d and %d\n", a, b)
   b = a + b
   a = b - a
   b = b - a
   fmt.Printf("After swapping, numbers are %d and %d\n", a, b)
}

func main(){
   swap(23, 45)
   swap(56, 100)
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Before swapping, numbers are 23 and 45
After swapping, numbers are 45 and 23
Before swapping, numbers are 56 and 100
After swapping, numbers are 100 and 56

更新于:2021 年 2 月 4 日

1K+ 浏览

开启你的 职业生涯

完成课程获取认证

开始
广告