交换变量x与变量y的值

方法一:利用中间变量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
using namespace std;
int main(){
	int x,y,t;
	x=10;
        y=30;
	cout<<"x="<<x<<" "<<"y="<<y<<endl;
	t=x;
	x=y;
	y=t;
	cout<<"x="<<x<<" "<<"y="<<y<<endl;
	
	return 0;
}

方法二:不需要中间变量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
using namespace std;
int main(){
	int x,y;
	x=10;
        y=30;
	cout<<"x="<<x<<" "<<"y="<<y<<endl;
	x=x+y;
	y=x-y;
	x=x-y;
	cout<<"x="<<x<<" "<<"y="<<y<<endl;
	
	return 0;
}

方法三:不需要中间变量

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
using namespace std;
int main(){
	int x,y;
	x=10;
        y=30;
	cout<<"x="<<x<<" "<<"y="<<y<<endl;
	x=x-y;
	y=x+y;
	x=y-x;
	cout<<"x="<<x<<" "<<"y="<<y<<endl;
	
	return 0;
}
Scroll to Top