C++交换两个数字的程序


有两种方法可以创建一个交换两个数字的程序。一种是使用临时变量,另一种是不使用第三个变量。这些方法将详细解释如下:

使用临时变量交换两个数字的程序

使用临时变量交换两个数字的程序如下所示。

示例

 在线演示

#include <iostream >
using namespace std;
int main() {
   int a = 10, b = 5, temp;
   temp = a;
   a = b;
   b = temp;
   cout<<"Value of a is "<<a<<endl;
   cout<<"Value of b is "<<b;
   return 0;
}

输出

Value of a is 5
Value of b is 10

在上面的程序中,有两个变量a和b存储两个数字。首先,a的值存储在temp中。然后,b的值存储在a中。最后,temp的值存储在b中。之后,a和b的值被交换。

temp = a;
a = b;
b = temp;

然后显示a和b的值。

cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;

不使用第三个变量交换两个数字的程序

不使用第三个变量交换两个数字的程序如下所示:

示例

 在线演示

#include <iostream>
using namespace std;
int main() {
   int a = 10, b = 5;
   a = a+b;
   b = a-b;
   a = a-b;
   cout<<"Value of a is "<<a<<endl;
   cout<<"Value of b is "<<b;
   return 0;
}

输出

Value of a is 5
Value of b is 10

在上面的程序中,首先将a和b的和存储在a中。然后,将a和b的差存储在b中。最后,将a和b的差存储在b中。最终,a和b的值被交换。

a = a+b;
b = a-b;
a = a-b;

然后显示a和b的值。

cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;

更新于:2020年6月24日

2K+ 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.