银行排队系统c语言实现
时间: 2023-11-18 17:11:44 浏览: 99
银行排队系统是一个典型的模拟系统,可以使用C语言实现。下面是一个简单的银行排队系统的C语言实现。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define MAX_QUEUE_SIZE 100
#define MAX_SERVICE_TIME 60
typedef struct {
int id; // 顾客编号
int arrive_time; // 到达时间
int service_time; // 服务时间
} Customer;
typedef struct {
Customer data[MAX_QUEUE_SIZE];
int front; // 队头指针
int rear; // 队尾指针
} Queue;
void init_queue(Queue *q);
int is_empty(Queue *q);
int is_full(Queue *q);
int enqueue(Queue *q, Customer c);
Customer dequeue(Queue *q);
Customer get_front(Queue *q);
int main()
{
Queue q;
init_queue(&q);
srand(time(NULL)); // 初始化随机数种子
int total_time = 0; // 总时间
int total_customer = 0; // 总顾客数
int total_service_time = 0; // 总服务时间
int max_wait_time = 0; // 最长等待时间
int i;
for (i = 0; i < 10; i++) {
Customer c;
c.id = i + 1;
c.arrive_time = rand() % 30 + 1; // 到达时间随机生成
c.service_time = rand() % MAX_SERVICE_TIME + 1; // 服务时间随机生成
printf("顾客%d:到达时间:%d,服务时间:%d\n", c.id, c.arrive_time, c.service_time);
if (c.arrive_time > total_time) { // 空闲时间
total_time = c.arrive_time;
}
if (!is_full(&q)) { // 队列未满,顾客入队
enqueue(&q, c);
} else {
printf("排队人数已满,顾客%d无法入队!\n", c.id);
}
while (!is_empty(&q)) { // 处理队列中的顾客
Customer front = get_front(&q);
if (front.arrive_time > total_time) { // 空闲时间
total_time = front.arrive_time;
}
if (total_service_time + front.service_time <= total_time) { // 顾客可以立即服务
front = dequeue(&q);
total_service_time += front.service_time;
total_customer++;
int wait_time = total_time - front.arrive_time;
if (wait_time > max_wait_time) {
max_wait_time = wait_time;
}
printf("顾客%d:等待时间:%d,开始服务时间:%d,结束服务时间:%d\n", front.id, wait_time, total_time, total_time + front.service_time);
} else {
break;
}
}
printf("当前时间:%d\n", total_time);
printf("--------------------------------------------------\n");
}
printf("总顾客数:%d,总等待时间:%d,最长等待时间:%d\n", total_customer, total_time - total_service_time, max_wait_time);
return 0;
}
void init_queue(Queue *q)
{
q->front = q->rear = 0;
}
int is_empty(Queue *q)
{
return q->front == q->rear;
}
int is_full(Queue *q)
{
return (q->rear + 1) % MAX_QUEUE_SIZE == q->front;
}
int enqueue(Queue *q, Customer c)
{
if (is_full(q)) {
return 0;
} else {
q->data[q->rear] = c;
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
return 1;
}
}
Customer dequeue(Queue *q)
{
Customer c;
if (is_empty(q)) {
c.id = -1;
return c;
} else {
c = q->data[q->front];
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return c;
}
}
Customer get_front(Queue *q)
{
Customer c;
if (is_empty(q)) {
c.id = -1;
return c;
} else {
return q->data[q->front];
}
}
```
在这个银行排队系统的C语言实现中,使用了一个队列(Queue)来存储排队的顾客。每个顾客都有一个编号、到达时间和服务时间。顾客到达时间和服务时间都是随机生成的。每个顾客到达后,如果队列未满,则将顾客入队;否则,顾客无法入队。
在处理顾客时,先处理队列中已经到达并且可以立即服务的顾客,如果队列中还有顾客需要等待,则等待时间就是当前时间减去顾客到达时间。在处理完队列中的顾客后,就更新总服务时间和总时间,并打印出当前时间。
最后,统计总顾客数、总等待时间和最长等待时间。