不用中间变量交换两个数

版权声明:快乐源自分享,欢迎高手指正错误。 https://blog.csdn.net/gdnh22a/article/details/82774409

要求:不用第三变量将a和b两个值交换。

方法:用 ^ 异或解决,同桌是这样解决的,很聪明。

#include<stdio.h>
int main()
{
int a=13,b=31;
printf(“交换前:a=%d b=%d \n”,a,b);
b=a^b;//得出中间值
a=a^b;//a里存的是b值
b=a^b;//b里存的是a值
printf(“交换后:a=%d b=%d\n”,a,b);
return 0;
}

猜你喜欢

转载自blog.csdn.net/gdnh22a/article/details/82774409