C语言习题_冒泡排序容易出现的错误
21视频教程网3月21日整理
错误实例如下:
# 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
C语言编辑部纠错:
void rank(books book[], int n)
{
int i,j,tnum;
char tname[30],tpublisher[15];
float tprice;
struct books tmp;
for (i=0 ; i<n ; i++)
{
for (j=i+1 ; j<n ; j++)
if(book[i].price>book[j].price)
{
tmp = book[i];
book[i] = book[j];
book[j] = tmp;
}
}
for (i=0 ; i<n ; i++)
{
printf("%s %s %d %.2f\n",book[i].name,book[i].publisher,book[i].num,book[i].price);
}
}
出错的原因在于:
if(book[i].price>book[i+1].price)
to
if(book[j].price>book[j+1].price)
下面花括号里的i也相应地改为j
C语言编辑部
Word教程网 | Excel教程网 | Dreamweaver教程网 | Fireworks教程网 | PPT教程网 | FLASH教程网 | PS教程网 |
HTML教程网 | DIV CSS教程网 | FLASH AS教程网 | ACCESS教程网 | SQL SERVER教程网 | C语言教程网 | JAVASCRIPT教程网 |
ASP教程网 | ASP.NET教程网 | CorelDraw教程网 |