用C语言写一个用队列实现的银行模拟取钱代码
时间: 2023-04-05 20:04:52 浏览: 76
好的,以下是用C语言写一个用队列实现的银行模拟取钱代码的示例:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 100
typedef struct {
int id;
int amount;
} Customer;
typedef struct {
Customer data[MAX_QUEUE_SIZE];
int front;
int rear;
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
int isQueueEmpty(Queue *q) {
return q->front == q->rear;
}
int isQueueFull(Queue *q) {
return (q->rear + 1) % MAX_QUEUE_SIZE == q->front;
}
void enqueue(Queue *q, Customer c) {
if (isQueueFull(q)) {
printf("Queue is full!\n");
exit(1);
}
q->data[q->rear] = c;
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}
Customer dequeue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty!\n");
exit(1);
}
Customer c = q->data[q->front];
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return c;
}
int main() {
Queue q;
initQueue(&q);
int n;
printf("Enter the number of customers: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
Customer c;
c.id = i;
printf("Enter the amount of money for customer %d: ", i);
scanf("%d", &c.amount);
enqueue(&q, c);
}
int total = 0;
while (!isQueueEmpty(&q)) {
Customer c = dequeue(&q);
printf("Customer %d withdraws %d yuan.\n", c.id, c.amount);
total += c.amount;
}
printf("Total amount of money withdrawn: %d yuan.\n", total);
return 0;
}
```
这个程序使用队列来模拟银行的取款过程。首先,用户需要输入要模拟的客户数量,然后输入每个客户要取款的金额。程序将每个客户的信息存储在队列中,然后按照队列的顺序处理每个客户,输出客户的编号和取款金额,并计算所有客户取款的总金额。