请看看这个冒泡排序
# include <stdio.h># include <string.h>
/*结构体定义*/
struct books
{
char name[30], publisher[15];
int num;
float price;
}book[50];
void rank(books book[], int n);
int main()
{
int i,n;
printf("请输入图书数量:");
scanf("%d",&n);
printf("请分别输入书名、出版社、数量、单价(以空格分开):\n");
for (i=0 ; i<n ; i++)
{
scanf("%s%s%d%f",&book[i].name,&book[i].publisher,&book[i].num,&book[i].price);
}
printf("\n");
rank(book,n);
return 0;
}
/*排序,输出函数rank*/
void rank(books book[], int n)
{
int i,j,tnum;
char tname[30],tpublisher[15];
float tprice;
for (i=0 ; i<n-1 ; i++)
{
for (j=0 ; j<n-i-1 ; j++)
if(book[i].price>book[i+1].price)
{
strcpy(tname,book[i].name), strcpy(book[i].name,book[i+1].name), strcpy(book[i+1].name,tname);//交换书名
strcpy(tpublisher,book[i].publisher), strcpy(book[i].publisher,book[i+1].publisher), strcpy(book[i+1].publisher,tpublisher);//交换出版商
tnum=book[i].num, book[i].num=book[i+1].num, book[i+1].num=tnum;//交换数目
tprice=book[i].price, book[i].price=book[i+1].price, book[i+1].price=tprice;//交换单价
}
}
for (i=0 ; i<n ; i++)
{
printf("%s %s %d %.2f\n",book[i].name,book[i].publisher,book[i].num,book[i].price);
}
}
按说输入以下内容:
3
a aa 50 25.5
b bb 30 31.55
c cc 60 18.3
时应该出现的结果是:
c cc 60 18.3
a aa 50 25.5
b bb 30 31.55
可为何却出现:
a aa 50 25.5
c cc 60 18.3
b bb 30 31.55