酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

在 dev-c++上面 定义一个包含图书信息(书号、书名、价格)的链表,读入相应的图书数据来完成图书信息表的创建,然后根据指定的最佳位置的序号,查找该位置上的图书,输出相应图书的信息。 输入 总计n+m+2行。首先输入n+1行,其中,第一行是图书数目n,后n行是n本图书的信息(书号、书名、价格),每本图书信息占一行,书号、书名、价格用空格分隔,价格之后没有空 格。其中书号和书名为字符串类型,价格为浮点数类型。然后输入m+1行,其中,第一行是一个整数m,代表查找m次,后m行每行内容为,个整数,代表待查找的图书的位置序号。 输出 输出m行 若查找成功: 输出内容为第谈次查询的指定位置上的一本图书的信息(书号、书名、价格),书号、书名、价格用空格分隔,其中价格输出保留两位小数。 若查找失败:只输 出以下提示:抱歉,最住位置上的图书不存在! 样例输入复制 8 9787302257646 data-structure 35.00 9787302164340 operating- system 50.00 9787302219972 software-engineer 32.00 97873022

在 Dev-C++ 上实现一个简单的链表来存储图书信息,并根据用户的输入进行查找,可以按照下面的代码进行: ```cpp #include <iostream> #include <iomanip> #include <string> using namespace std; struct Book { string id; // 书号 string title; // 书名 float price; // 价格 Book* next; // 指向下一个节点的指针 }; class BookList { public: BookList() : head(nullptr) {} void addBook(const string& id, const string& title, float price) { Book* newBook = new Book{id, title, price, nullptr}; if (head == nullptr) { head = newBook; } else { Book* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = newBook; } } Book* getBookAt(int position) { Book* current = head; for (int i = 1; i < position && current != nullptr; ++i) { current = current->next; } return current; } ~BookList() { while (head != nullptr) { Book* temp = head; head = head->next; delete temp; } } private: Book* head; }; int main() { int n; cin >> n; BookList bookList; // 读入图书信息 for (int i = 0; i < n; ++i) { string id, title; float price; cin >> id >> title >> price; // 假设书名不含空格 bookList.addBook(id, title, price); } int m; cin >> m; // 进行查找 for (int i = 0; i < m; ++i) { int position; cin >> position; Book* book = bookList.getBookAt(position); if (book != nullptr) { cout << book->id << " " << book->title << " " << fixed << setprecision(2) << book->price << endl; } else { cout << "抱歉,指定位置上的图书不存在!" << endl; } } return 0; } ``` 代码说明: 1. 结构体定义:`Book` 结构体包含书号、书名、价格和指向下一个节点的指针。 2. 链表管理类:`BookList` 类负责管理链表,提供添加书籍和获取指定位置书籍的功能。 3. 添加书籍:通过 `addBook` 方法在链表尾部添加新的书籍。 4. 查找书籍:通过 `getBookAt` 方法根据位置查找书籍,返回相应的书籍指针。 5. 主函数: - 读入图书数量及每本书的信息并存入链表。 - 读入查询次数和查询位置,输出对应的图书信息或错误提示。 注意事项: - 为了简化输入,假设书名没有空格。如果需要处理书名中的空格,可以考虑使用 `getline` 并根据需要调整输入方式。 [2024-12-18 09:04:49 | AI写代码神器 | 1650点数解答]

相关提问