用c语言定义一个包含图书信息(书号、书名、价格)的顺序表,读入相应的图书数据完成图书信息表的创建,然后将图书按照价格降序排序,逐行输出排序后每本图书的信息。
时间: 2024-05-03 19:22:08 浏览: 50
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TITLE_LEN 50
#define MAX_NUM_BOOKS 100
typedef struct {
int book_id;
char title[MAX_TITLE_LEN];
float price;
} Book;
void swap(Book *a, Book *b) {
Book tmp = *a;
*a = *b;
*b = tmp;
}
void sort_books(Book *books, int n) {
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (books[j].price < books[j + 1].price) {
swap(&books[j], &books[j + 1]);
}
}
}
}
int main() {
Book books[MAX_NUM_BOOKS];
int n, i;
printf("Enter number of books: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter book %d info:\n", i + 1);
printf("Book ID: ");
scanf("%d", &books[i].book_id);
printf("Title: ");
scanf("%s", books[i].title);
printf("Price: ");
scanf("%f", &books[i].price);
}
sort_books(books, n);
printf("\nBook info sorted by price in descending order:\n");
for (i = 0; i < n; i++) {
printf("%d\t%s\t%.2f\n", books[i].book_id, books[i].title, books[i].price);
}
return 0;
}
```
阅读全文