不適用 其他的變數交換兩個數值
#include<stdio.h> #include <stdlib.h> void swap1(int& a,int& b) //使用中間變數交換兩個值 { int temp = a; a = b; b = temp; } void swap2(int& a, int& b) //只用加法、減法、乘法也可以交換兩個值 { a = a + b; b = a - b; a = a - b; } void swap3(int& a, int& b) //使用位運算也可以交換兩個值 { a = a^b; b = a^b; a = a^b; } void main1mianshiti7() { int a1 = 1, b1 = 2; int a2 = 10, b2 = 15; int a3 = 78, b3 = 90; int a = 2147483647, b = 1; printf("a1=%p,b1=%p", &a1, &b1); swap1(a1, b1); swap2(a2, b2); swap3(a3, b3); printf("swap after~~~~~~~~~~~~~\n"); printf("a1=%d,b1=%d\n", a1, b1); printf("a2=%d,b2=%d\n", a2, b2); printf("a3=%d,b3=%d\n", a3, b3); swap2(a, b); printf("a=%d,b=%d\n", a, b); system("pause"); }