一、借助第三个变量
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 2, b = 8, temp = 0;
temp = a;
a = b;
b = temp;
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;
}