int i,j;
printf("The order is\n");//为什么加一个中间变量k就能输出结果
for(i=0;i<N-1;i++)
{
for(j=i+1;j<N;j++)
if(stu[j].score>stu[i].score)
temp=stu[j];stu[j]=stu[i];stu[i]=temp;
}
//输出五人成绩//
for(i=0;i<N;i++)
{
printf("%6d %8s %6.2f\n",stu[i].num,stu[i].name,stu[i].score);
}
printf("\n");
return 0;
}
如果不用中间变量交换,你可以考虑用XOR Swap
#include <stdio.h>
/** Inplace swap using the XOR operation */
void xor_swap(int *a, int *b)
{
if (a != b)
{
*a ^= *b; // a = A XOR B
*b ^= *a; // b = B XOR ( A XOR B ) = A
*a ^= *b; // a = ( A XOR B ) XOR A = B
}
}
void xor_swapf(float *a, float *b)
{
xor_swap((int *)a, (int *)b);
}
int main()
{
int a = 1, b = 2;
float c = 1.23, d = 4.56;
printf("before:\n");
printf("a=%d b=%d\n", a, b);
printf("c=%f d=%f\n", c, d);
xor_swap(&a, &b);
xor_swapf(&c, &d);
printf("after:\n");
printf("a=%d b=%d\n", a, b);
printf("c=%f d=%f\n", c, d);
return 0;
}
$ gcc -Wall main.c
$ ./a.out
before:
a=1 b=2
c=1.230000 d=4.560000
after:
a=2 b=1
c=4.560000 d=1.230000