- 使用临时变量
#include<iostream>
using namespace std;
int main()
{
int a=2,b=18,temp;
cout << "交换之前:" << "a=" << a << ",b=" << b;
temp=a;a=b;b=temp;
cout << endl << "交换之后:" << "a=" << a << ",b=" << b << endl;
system("pause");
return 0;
}
- 不使用临时变量
#include<iostream>
using namespace std;
int main()
{
int a=20,b=30;
cout << "交换之前:" << "a=" << a << ",b=" << b;
a=a+b;
b=a-b;
a=a-b;
cout << endl << "交换之后:" << "a=" << a << ",b=" << b << endl;
system("pause");
return 0;
}