c语言编程题;从键盘输入N本图书的书名(书名长度不超过10个汉字)和单价,按单价从高到低顺序排序后输出图书

c语言编程题;从键盘输入N本图书的书名(书名长度不超过10个汉字)和单价,按单价从高到低顺序排序后输出图书

#include <stdio.h>

#include <stdlib.h>

#define max_N 10000


/*定义书的结构体

 *name,书的名字

 *price,书的单价

 */

struct Book {

    char name[21];

    double price;

} book[max_N];


//定义快速排序的比较函数

int cmp(const void *a, const void *b) {

     return (*(struct Book *)b).price > (*(struct Book *)a).price ? 1 : -1;

}


int main()

{

    int N, i;

   

    printf("\n请输入书的数量:");

    scanf("%d", &N);

   

    printf("\n请依次输入%d本书的书名、价格:\n\n", N);

    for (i = 0; i < N; ++i) {

        scanf("%s %lf", book[i].name, &book[i].price);

    }

   

    //快速排序

    qsort(book, N, sizeof(struct Book), cmp);

   

    printf("\n%d本书按单价从高到低排序如下:\n\n", N);

    for (i = 0; i < N; ++i) {

        printf("%s\n", book[i].name);

    }

   

    return 0;

}


温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-15
#include<stdio.h>
struct Node
{
char name[21];
int price;
struct Node * next;
};

int main(void)
{
int i = 0,num;
struct Node * head,*tmp,*find;
head = NULL;
printf("Input book num: ");
scanf("%d",&num);
while(i < num)
{
tmp = (struct Node *) malloc(sizeof(struct Node));
printf("Input num %d book name : ",i+1);
scanf("%s",tmp->name);
printf("Input num %d book price: ",i + 1);
scanf("%d",tmp->price);
if(head == NULL)
head = tmp;
else if(tmp->price > head->price)
{
tmp->next = head;
head = tmp;
}
else
{
find = head;
while(find->next)
{
if(find-next->price < tmp->price)
break;
find = find->next;
}
tmp->next = find->next;
find->next = tmp;
}
i ++;
}
while(head)
{
printf("Name : %s ,price : %d \n",head->namd,head->price);
find = head;
head = head->next;
free(find);
}
return 0;
}
相似回答