通过输入id号还书(C语言)
时间: 2023-09-24 13:11:48 浏览: 47
好的,你可以参考以下代码实现通过输入id号还书的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_BOOKS 100 // 最大书籍数量
struct Book {
int id; // 书籍编号
char title[100]; // 书籍名称
char author[50]; // 作者
int year; // 出版年份
int is_borrowed; // 是否被借出,0-未借出,1-已借出
};
struct Library {
struct Book books[MAX_BOOKS]; // 书籍数组
int num_books; // 当前书籍数量
};
// 初始化图书馆
void init_library(struct Library *lib) {
lib->num_books = 0;
}
// 添加书籍
void add_book(struct Library *lib, int id, char *title, char *author, int year) {
// 检查书籍数量是否已达到上限
if (lib->num_books >= MAX_BOOKS) {
printf("Error: library is full.\n");
return;
}
// 检查书籍是否已存在
for (int i = 0; i < lib->num_books; i++) {
if (lib->books[i].id == id) {
printf("Error: book id already exists.\n");
return;
}
}
// 添加书籍
struct Book book = {id, title, author, year, 0};
lib->books[lib->num_books] = book;
lib->num_books++;
}
// 根据id查找书籍,返回书籍在数组中的下标,未找到返回-1
int find_book(struct Library *lib, int id) {
for (int i = 0; i < lib->num_books; i++) {
if (lib->books[i].id == id) {
return i;
}
}
return -1;
}
// 借出书籍
void borrow_book(struct Library *lib, int id) {
int index = find_book(lib, id);
if (index == -1) {
printf("Error: book not found.\n");
return;
}
if (lib->books[index].is_borrowed) {
printf("Error: book is already borrowed.\n");
return;
}
lib->books[index].is_borrowed = 1;
printf("Book \"%s\" has been borrowed successfully.\n", lib->books[index].title);
}
// 归还书籍
void return_book(struct Library *lib, int id) {
int index = find_book(lib, id);
if (index == -1) {
printf("Error: book not found.\n");
return;
}
if (!lib->books[index].is_borrowed) {
printf("Error: book is not borrowed.\n");
return;
}
lib->books[index].is_borrowed = 0;
printf("Book \"%s\" has been returned successfully.\n", lib->books[index].title);
}
// 显示所有书籍
void display_books(struct Library *lib) {
printf("ID\tTitle\tAuthor\tYear\tStatus\n");
for (int i = 0; i < lib->num_books; i++) {
printf("%d\t%s\t%s\t%d\t%s\n", lib->books[i].id, lib->books[i].title, lib->books[i].author, lib->books[i].year, lib->books[i].is_borrowed ? "Borrowed" : "Available");
}
}
int main() {
struct Library lib;
init_library(&lib);
// 添加示例书籍
add_book(&lib, 1001, "The Catcher in the Rye", "J.D. Salinger", 1951);
add_book(&lib, 1002, "To Kill a Mockingbird", "Harper Lee", 1960);
add_book(&lib, 1003, "1984", "George Orwell", 1949);
add_book(&lib, 1004, "Animal Farm", "George Orwell", 1945);
// 显示所有书籍
display_books(&lib);
// 借出书籍
borrow_book(&lib, 1001);
borrow_book(&lib, 1002);
// 显示所有书籍
display_books(&lib);
// 归还书籍
return_book(&lib, 1001);
// 显示所有书籍
display_books(&lib);
return 0;
}
```
其中,通过调用 `borrow_book` 和 `return_book` 函数可以实现借出和归还书籍的功能。你可以根据实际需要修改代码,以实现更加复杂的功能。