方法一:
创建临时变量
#include<stdio.h> #include<stdlib.h> int main() { int a = 1, b = 2; int temp = a;//创建临时变量temp a = b; b = temp; printf("a=%d,b=%d", a, b); system("pause"); return 0; }
方法二:
通过异或
#include<stdio.h> #include<stdlib.h> int main() { int a = 1, b = 2; a = a^b; b = b^a; a = a^b; printf("a=%d,b=%d", a, b); system("pause"); return 0; }
方法三:
通过加减(或乘除)
#include<stdio.h> #include<stdlib.h> int main() { int a = 1, b = 2; a = a + b;//a=a-b也可以 b = a - b; a = a - b; printf("a=%d,b=%d", a, b); system("pause"); return 0; }
方法四:
利用指针交换两个变量的值
#include<stdio.h> #include<stdlib.h> void swap(int *p1, int *p2) { char temp = *p1; *p1 = *p2; *p2 = temp; } int main() { int a = 1, b = 2; swap(&a, &b); printf("a=%d,b=%d", a, b); system("pause"); return 0; }
时间: 2024-10-05 18:47:37