用c语言定义一个包含图书信息(书号、书名、价格)的顺序表,读入相应的图书数据完成图书信息表的创建,然后将图书按照价格降序排序,逐行输出排序后每本图书的信息。
时间: 2024-05-09 22:17:22 浏览: 146
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100 // 最大图书数量
// 图书结构体,包含书号、书名和价格
struct Book {
int book_id;
char book_name[50];
double book_price;
};
// 图书表结构体,包含图书数量和图书数组
struct BookTable {
int count;
struct Book books[MAX_BOOKS];
};
// 向图书表中添加一本图书
void addBook(struct BookTable *table, struct Book book) {
if (table->count >= MAX_BOOKS) {
printf("图书数量已达到最大值%d,无法再添加图书\n", MAX_BOOKS);
return;
}
table->books[table->count] = book;
table->count++;
}
// 比较函数,用于qsort排序
int cmp(const void *a, const void *b) {
struct Book *book1 = (struct Book *)a;
struct Book *book2 = (struct Book *)b;
if (book1->book_price < book2->book_price) {
return 1;
} else if (book1->book_price > book2->book_price) {
return -1;
} else {
return 0;
}
}
int main() {
struct BookTable table = {0}; // 初始化图书表
int book_id;
char book_name[50];
double book_price;
printf("请输入图书信息,格式为:书号 书名 价格(每本图书占一行,输入-1结束)\n");
while (1) {
scanf("%d", &book_id);
if (book_id == -1) {
break;
}
scanf("%s %lf", book_name, &book_price);
struct Book book = {book_id, book_name, book_price};
addBook(&table, book);
}
// 使用qsort对图书表进行价格降序排序
qsort(table.books, table.count, sizeof(struct Book), cmp);
// 逐行输出排序后的图书信息
printf("图书信息表(按价格降序排列):\n");
printf("书号\t书名\t\t价格\n");
for (int i = 0; i < table.count; i++) {
printf("%d\t%s\t\t%.2lf\n", table.books[i].book_id, table.books[i].book_name, table.books[i].book_price);
}
return 0;
}
```
阅读全文