1.使用中间值temp
int a = 5,b = 8;
int tmp;
tmp = a;
a = b;
b = tmp;
输出结果:
a=8,b=5
2.使用求和方式
int a = 5,b = 8;
//不用中间值
a = a+b;
b = a-b;
a = a-b;
输出结果:
a=8,b=5
3.使用异或
int main(int argc, const char * argv[]) {
int a = 5,b = 8;
//异或
a = a^b;
b = a^b;
a = a^b;
printf("a=%d,b=%d \n",a,b);
return 0;
}
输出结果:
a=8,b=5
4.函数实现两个变量的值交换
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main(int argc, const char * argv[]) {
int a =3,b= 4;
swap(&a,&b); //a和b的值进行了交换
printf("a=%d,b=%d",a,b);
return 0;
}
输出结果:
a=4,b=3