用C写一段图书馆借阅和还书的函数
时间: 2024-03-23 21:36:04 浏览: 16
好的,下面是一段简单的图书馆借阅和还书的函数的 C 代码。具体实现可能需要根据具体情况进行调整和完善。
```
#include <stdio.h>
#include <string.h>
// 最大书籍数量
#define MAX_BOOKS 100
// 书籍结构体
typedef struct {
char title[50];
char author[50];
int id;
int borrowed; // 0 表示未被借出,1 表示已被借出
} Book;
// 图书馆结构体
typedef struct {
Book books[MAX_BOOKS];
int n_books; // 当前书籍数量
} Library;
// 初始化图书馆
void initLibrary(Library* lib) {
lib->n_books = 0;
}
// 添加一本书籍到图书馆
void addBook(Library* lib, const char* title, const char* author, int id) {
if (lib->n_books >= MAX_BOOKS) {
printf("Error: no more space for books.\n");
return;
}
Book* book = &lib->books[lib->n_books];
strcpy(book->title, title);
strcpy(book->author, author);
book->id = id;
book->borrowed = 0;
lib->n_books++;
}
// 根据 ID 查找书籍在数组中的下标
int findBookIndexById(Library* lib, int id) {
for (int i = 0; i < lib->n_books; i++) {
if (lib->books[i].id == id) {
return i;
}
}
return -1;
}
// 借阅书籍
void borrowBook(Library* lib, int id) {
int index = findBookIndexById(lib, id);
if (index == -1) {
printf("Error: book with ID %d not found.\n", id);
return;
}
if (lib->books[index].borrowed) {
printf("Error: book with ID %d is already borrowed.\n", id);
return;
}
lib->books[index].borrowed = 1;
printf("Book \"%s\" by %s (ID %d) has been borrowed.\n",
lib->books[index].title, lib->books[index].author, lib->books[index].id);
}
// 还书
void returnBook(Library* lib, int id) {
int index = findBookIndexById(lib, id);
if (index == -1) {
printf("Error: book with ID %d not found.\n", id);
return;
}
if (!lib->books[index].borrowed) {
printf("Error: book with ID %d is not borrowed.\n", id);
return;
}
lib->books[index].borrowed = 0;
printf("Book \"%s\" by %s (ID %d) has been returned.\n",
lib->books[index].title, lib->books[index].author, lib->books[index].id);
}
// 测试函数
int main() {
Library lib;
initLibrary(&lib);
addBook(&lib, "C Programming Language", "Brian Kernighan and Dennis Ritchie", 1);
addBook(&lib, "The Art of Computer Programming", "Donald Knuth", 2);
borrowBook(&lib, 1);
returnBook(&lib, 2);
borrowBook(&lib, 2);
returnBook(&lib, 1);
return 0;
}
```
以上代码实现了一个简单的图书馆借阅和还书功能。可以通过 `addBook()` 函数添加书籍,通过 `borrowBook()` 函数借阅书籍,通过 `returnBook()` 函数还书。在 `Book` 结构体中,使用 `borrowed` 属性表示书籍是否已经被借出。在 `findBookIndexById()` 函数中,根据书籍 ID 查找书籍在数组中的下标。