有两种方法可以创建交换两个数字的程序。一种涉及使用临时变量,第二种不使用第三种变量。这些详细解释如下-
使用临时变量交换两个数字的程序如下。
#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;