定义一个包含图书信息(书号、书名、价格)的顺序表,读入相应的图书数据来完成图书信息表的创建,然后查找价格最高的图书,输出相应图书的信息。用c++实现
时间: 2023-12-23 19:05:23 浏览: 117
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct Book {
int bookId;
char bookName[50];
float price;
} Book;
typedef struct SeqList {
Book data[MAX_SIZE];
int length;
} SeqList;
void init(SeqList* list) {
list->length = 0;
}
void insert(SeqList* list, Book book) {
if (list->length >= MAX_SIZE) {
printf("List is full.\n");
return;
}
list->data[list->length++] = book;
}
void printBook(Book book) {
printf("Book ID: %d\n", book.bookId);
printf("Book Name: %s\n", book.bookName);
printf("Price: %.2f\n", book.price);
}
void printList(SeqList list) {
for (int i = 0; i < list.length; i++) {
printf("Book #%d:\n", i + 1);
printBook(list.data[i]);
printf("\n");
}
}
Book findMaxPriceBook(SeqList list) {
Book maxPriceBook = list.data[0];
for (int i = 1; i < list.length; i++) {
if (list.data[i].price > maxPriceBook.price) {
maxPriceBook = list.data[i];
}
}
return maxPriceBook;
}
int main() {
SeqList list;
init(&list);
// 读入图书数据
int n;
printf("Enter the number of books: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
Book book;
printf("Enter Book #%d information:\n", i + 1);
printf("Book ID: ");
scanf("%d", &book.bookId);
printf("Book Name: ");
scanf("%s", book.bookName);
printf("Price: ");
scanf("%f", &book.price);
insert(&list, book);
}
printf("\nAll Books:\n");
printList(list);
Book maxPriceBook = findMaxPriceBook(list);
printf("\nBook with Max Price:\n");
printBook(maxPriceBook);
return 0;
}
阅读全文