我有以下代码,其中我必须按字母顺序对书名进行排序。这是我拥有的代码,不确定如何执行实际排序。任何有关如何对 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;
}
最佳答案
我在你的代码中发现了一些问题:
您必须初始化一个 book 结构数组,而不是 book1 和 book2,声明:
struct books book[nnn] /* where nnn is the maximum number of book */
您必须在 do while 循环中使用从 0 开始的计数器(应该是 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)
关于c - C 中的结构元素排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585344/