借书后打印出借书后的新书单
时间: 2023-08-25 15:04:43 浏览: 50
以下是修改后的代码,借书后会打印出新的书单:
```c
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
struct Book {
char title[50];
char author[50];
int id;
int borrowed;
};
struct Book books[MAX_BOOKS];
int num_books = 0;
void add_book(char* title, char* author, int id) {
struct Book book;
strcpy(book.title, title);
strcpy(book.author, author);
book.id = id;
book.borrowed = 0;
books[num_books++] = book;
}
void borrow_book(int id) {
for (int i = 0; i < num_books; i++) {
if (books[i].id == id && !books[i].borrowed) {
books[i].borrowed = 1;
printf("You have borrowed the book %s by %s\n", books[i].title, books[i].author);
printf("New book list:\n");
print_books();
return;
}
}
printf("Sorry, the book with id %d is not available for borrowing\n", id);
}
void return_book(int id) {
for (int i = 0; i < num_books; i++) {
if (books[i].id == id && books[i].borrowed) {
books[i].borrowed = 0;
printf("You have returned the book %s by %s\n", books[i].title, books[i].author);
printf("New book list:\n");
print_books();
return;
}
}
printf("Sorry, the book with id %d was not borrowed by you\n", id);
}
void print_books() {
printf("Available Books:\n");
for (int i = 0; i < num_books; i++) {
if (!books[i].borrowed) {
printf("%d - %s by %s\n", books[i].id, books[i].title, books[i].author);
}
}
}
int main() {
add_book("The Great Gatsby", "F. Scott Fitzgerald", 1);
add_book("To Kill a Mockingbird", "Harper Lee", 2);
add_book("1984", "George Orwell", 3);
borrow_book(1);
borrow_book(2);
return_book(1);
return 0;
}
```
在这个示例中,我们修改了 `borrow_book` 和 `return_book` 函数,在借阅或归还成功后打印出新的书单。`print_books` 函数不变,用于输出当前可用的书籍列表。
在 `main` 函数中,我们添加了三本书,借阅了前两本书并归还了第一本书,每次借阅或归还后都会打印出新的书单。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)