写一个图书借阅和归还的代码c语言
时间: 2024-03-23 10:39:16 浏览: 65
以下是一个简单的图书借阅和归还的代码示例,基于C语言:
```c
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
struct Book {
char title[50];
char author[50];
int id;
int is_available;
};
int num_books = 0;
struct Book library[MAX_BOOKS];
void add_book(char title[], char author[], int id) {
if (num_books >= MAX_BOOKS) {
printf("Error: Library is full\n");
return;
}
struct Book new_book;
strcpy(new_book.title, title);
strcpy(new_book.author, author);
new_book.id = id;
new_book.is_available = 1;
library[num_books] = new_book;
num_books++;
printf("Book added successfully\n");
}
void print_books() {
printf("Books in the library:\n");
for (int i = 0; i < num_books; i++) {
printf("%d: %s by %s", library[i].id, library[i].title, library[i].author);
if (library[i].is_available) {
printf(" - Available\n");
} else {
printf(" - Not available\n");
}
}
}
void borrow_book(int id) {
for (int i = 0; i < num_books; i++) {
if (library[i].id == id) {
if (library[i].is_available) {
library[i].is_available = 0;
printf("Book borrowed successfully\n");
} else {
printf("Error: Book is not available for borrowing\n");
}
return;
}
}
printf("Error: Book not found\n");
}
void return_book(int id) {
for (int i = 0; i < num_books; i++) {
if (library[i].id == id) {
if (!library[i].is_available) {
library[i].is_available = 1;
printf("Book returned successfully\n");
} else {
printf("Error: Book is already available\n");
}
return;
}
}
printf("Error: Book not found\n");
}
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);
print_books();
borrow_book(1);
print_books();
return_book(1);
print_books();
return 0;
}
```
该代码包含以下功能:
- `add_book`:将一本新书添加到图书馆中。
- `print_books`:打印图书馆中所有书籍的列表。
- `borrow_book`:借阅一本书。
- `return_book`:归还一本书。
示例使用结构体来表示每本书,并使用布尔值来跟踪每本书是否可用。此外,示例代码还定义了一个数组来存储图书馆中的书籍。
在这个简单的示例中,并没有考虑到多人同时借阅或归还同一本书的情况。在实际情况中,需要更加复杂的代码来处理这种情况。
阅读全文
相关推荐
![](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)
![docx](https://img-home.csdnimg.cn/images/20241231044901.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)