关于两个变量交换的几种方法。

来源:互联网 发布:新百伦淘宝旗舰店 编辑:程序博客网 时间:2024/05/01 10:24

一、借助第三个变量

#include <stdio.h>#include <stdlib.h>int main(){int a = 2, b = 8;a = a + b;b = a - b;a = a - b;printf("a=%d  b=%d\n", a, b);system("pause");return 0;}


二,运用函数

#include <stdio.h>#include <stdlib.h>void swap(int *pa, int *pb){int tem = 0;tem = *pa;*pa = *pb;*pb = tem;}int main(){int a = 2;int b = 8;swap(&a, &b);printf("a=%d  b=%d\n",a, b);system("pause");return 0;}

三、不借助第三个变量、

1、

#include <stdio.h>#include <stdlib.h>int main(){int a = 2, b = 8;a = a + b;b = a - b;a = a - b;printf("a=%d  b=%d\n", a, b);system("pause");return 0;}

2、

#include <stdio.h>#include <stdlib.h>int main(){int a = 2;int b = 8;a = a^b;b = a^b;a = a^b;printf("a=%d  b=%d\n", a, b);system("pause");return 0;}


0 0