我有以下代码,我必须按字母顺序对书名进行排序。这是我的代码,不确定如何执行实际的排序。任何关于如何分类超过2本书的帮助也将受到赞赏,因为提示用户输入多达30本书。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct Books
{
char title[256];
char author[256];
char genre[256];
int qualityRATE;
int pages;
};
int numberbook = 1;
int casee;
int booksnumber;
int i;
int main()
{
char again;
do
{
printf("how many books will you be entering today?");
scanf("%i", &booksnumber);
printf("Enter the information for your book.\n Name\n Author\n Genre\n quality rating\n\n");
struct Books book1;
struct Books book2;
scanf("%s", book1.title);
scanf("%s", book2.title);
printf("The title of book %i is: %s\n", numberbook, book1.title);
printf("The title of book %i is: %s\n", numberbook, book2.title);
printf("how would you like to sort?\n 1: By title\n 2: by Author\n 3: by pages\n\n");
scanf("%i", &casee);
switch(casee)
{
case 1:
for(i = 1; i < booksnumber, i++;)
{
if(strcmp(book[i].title, book[i+1].title) < 0)
strcpy(book[i+1].title, book[i].title);
else
if(strcmp(book[i+1].title, book[i].title) < 0)
strcpy(book[i].title, book[i+1].title);
}
printf("\n%s\n", book1.title);
break;
case 2:
break;
}
printf("Another book?\n");
numberbook++;
scanf("%s", &again);
}
while(again == 'y');
return 0;
}
答案 0 :(得分:0)
我在你的代码中看到了一些问题:
您必须初始化一组图书结构,而不是book1和book2,声明:
struct books book[nnn] /* where nnn is the maximum number of book */
你必须使用一个从0开始进入do while循环的计数器(应该是booksnumber)
您必须使用book [booksnumber]来使用scanf并为每个scanf增加booksnumber。
如果你想要一个可靠的排序引擎,我建议你使用函数qsort(qsort是stdlib.h中的C库函数)
请参阅:www.cplusplus.com/reference/cstdlib/qsort
对项目进行排序的正确方法应该是以下代码:
struct Books app;
int i,j;
for(i=0;i<booksnumber;i++) {
for(j=i+1;j<booksnumber;j++) {
if (strcmp(book[i].title,book[j].title)<0) {
app=book[i];
book[j]=book[i];
book[i]=app;
}
}
}
我认为第一个for循环应该更好,如下所示,但我已经动态编写了这段代码,然后我还没有验证它的行为。
for(i=0;i<booksnumber-1;i++)
我没有验证排序的方向是否符合您的要求,如果不是,您可以更改比较的“符号”反转它。 IE:
if (strcmp(book[i].title,book[j].title)>0)
答案 1 :(得分:0)
只需两本书即可使用swap
。而且我认为您还需要交换所有图书属性,而不仅仅是标题:
void swapBook(struct Books *a, struct Books *b) {
struct Books c = *a; /* backup first book */
*a = *b; /* replace first book with second book */
*b = c; /* replace second book with the backup of first book */
}
然后你应该能够像这样使用它:
if ( strcmp(book[i].title, book[i+1].title) < 0 ) {
swapBook( &book[i], &book[i+1] );
}
对于两本以上的书籍,这不起作用,您需要使用qsort
。