方法1((使用算术运算符):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h>
int main() { int a = 10, b = 5; // algo to swap 'a' and 'b' a = a + b; // a becomes 15 b = a - b; // b becomes 10 a = a - b; // fonally a becomes 5 printf("After Swapping the value of: a = %d, b = %d ", a, b); return 0; } |
方法2(使用按位异或运算符):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h>
int main() { int a = 10, b = 5; // algo to swap 'a' and 'b' a = a ^ b; // a becomes (a ^ b) b = a ^ b; // b = (a ^ b ^ b), b becomes a a = a ^ b; // a = (a ^ b ^ a), a becomes b printf("After Swapping the value of: a = %d, b = %d ", a, b); return 0; } |