注册 登录
编程论坛 C语言论坛

求助大佬 一道结构题

曾几何时丨丨 发布于 2022-03-26 18:20, 1126 次点击
struct book

{

    char name[50];

    float price;

    int classification;   

};

输入n本书(n<=100),及每本书的书名,价格和分类(空格分隔输入数据),

请分别根据价格递增顺序排序,如果价格相同,则按照书名(ASCII码)递增排序。

最后输出排序后的结果,每行一本书详细信息,按照:书名,价格(保留2位小数),分类由逗号分隔。

例子:

输入:

3

program 35  1

history   35  2

cloudy-computing 57 1

输出

history,35.00,2

program,35.00,1

cloudy-computing,57.00,1
1 回复
#2
rjsp2022-03-27 00:42
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct book
{
    char name[50];
    float price;
    int classification;
};

int bookcmp( const void* a, const void* b )
{
    const struct book* p = (const struct book*)a;
    const struct book* q = (const struct book*)b;

    if( p->price < q->price ) return -1;
    if( p->price > q->price ) return +1;

    return strcmp(p->name,q->name);
}

int main( void )
{
    struct book books[100];
    size_t n;

    scanf( "%zu", &n );
    for( size_t i=0; i!=n; ++i )
        scanf( "%s%f%d", books[i].name, &books[i].price, &books[i].classification );

    qsort( books, n, sizeof(*books), &bookcmp );

    for( size_t i=0; i!=n; ++i )
        printf( "%s,%.2f,%d\n", books[i].name, books[i].price, books[i].classification );
}
1