如何交换二变量的值?
1.三变量法:通过一个中间变量来达到交换的目的。
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int a, b; 6 cin >> a >> b; 7 int c = a; 8 a = b; 9 b = c; 10 cout << a << ' '<<b << endl; 11 return 0; 12 }
2.不借助中间变量:加减法
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int a, b; 6 cin >> a >> b; 7 a = a + b; 8 b = a - b; 9 a = a - b; 10 cout << a << ' '<< b << endl; 11 return 0; 12 }
3.不借助中间变量:位运算法(异或)
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int a, b; 6 cin >> a >> b; 7 a = a^b; 8 b = a^b; 9 a = a^b; 10 cout << a << ' '<<b << endl; 11 return 0; 12 }
4.只改变输出顺序(针对算法竞赛)
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int a, b; 6 cin >> a >> b; 7 cout << b << ' '<<a << endl; 8 return 0; 9 }