方法一:三变量交换。
#include<stdio.h>int main(void)
{
int a,b
scanf("%d%d",&a,&b)
int t=aa=bb=t
printf("%d %d\n",a,b)
return 0
}
方法二:加减交换
#include<stdio.h>int main(void)
{
int a,b
scanf("%d%d",&a,&b)
a=a+b
b=a-b
a=a-b
printf("%d %d\n",a,b)
return 0
}
方法三:异或交换
#include<stdio.h>int main(void)
{
int a,b
scanf("%d%d",&a,&b)
a=a^bb=b^aa=a^b//可写成a^=b^=a^=b
printf("%d %d\n",a,b)
return 0
}
方法四(黑盒测试下):不交换
#include<stdio.h>int main(void)
{
int a,b
scanf("%d%d",&a,&b)
printf("%d %d\n",b,a)
return 0
}
楼上的这个a
=
a+b
b
=
a-b
a
=
a-b
是个方法,是符合我们数学思维的方法,也是最初接触C语言的人可能想到的方法。
但是这样编程很不直观,不如t=aa=bb=t来得快。
似乎在C++中有swap(a,
b)模板函数,直接实现a,b交换。
想玩高级一点的话,可采用“换标不换值”的方法,用数组元素作为数组的下标,这种方法换逻辑不换存储。
#include
<stdio.h>
void
main()
{
int
a=10,b=20
int
array1[2]
=
{10,20}
//存a、b值
int
array2[2]
=
{0,1}
//存下标
b
=
array1[array2[0]]
a
=
array1[array2[1]]
printf("a=%d,
b=%d\n",a,b)
}
这个方法在对结构体数组值交换中非常好用!因为结构体数组一般每个成员都有很多个值,如:
struct
student
{
int
num
double
score
char
name[20]
}stu[5]={{1,98,"ziguowen"},{2,88,"dongda"},{3,78,"haha"}}
//交换stu[0]和stu[1],需要
int
n
double
s
char
n[20]
n
=
stu[0].num
stu[0].num
=
stu[1].num
stu[1].num
=
n
s
=
stu[0].score
stu[0].score
=
stu[1].score
stu[1].score
=
s
strcpy(n,
stu[0].name)
strcpy(stu[0].name,
stu[1].name)
strcpy(stu[0].name,s)
//而用下标的话,一个赋值语句即可,直接交换stu[0]
和
stu[1]
下标后全部交换!