c语言简单的单服务台排队模型
时间: 2023-09-14 11:07:40 浏览: 39
以下是一个简单的单服务台排队模型的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_QUEUE_SIZE 10 // 队列最大长度
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) {
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;
}
void enqueue(Queue *q, Customer c) {
if (is_full(q)) {
printf("Queue is full.\n");
return;
}
q->data[q->rear] = c;
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}
Customer dequeue(Queue *q) {
if (is_empty(q)) {
printf("Queue is empty.\n");
Customer c;
c.id = -1;
return c;
}
Customer c = q->data[q->front];
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return c;
}
int main() {
srand(time(NULL)); // 初始化随机数种子
Queue queue;
init_queue(&queue);
int total_time = 0; // 总时间
int wait_time = 0; // 等待时间
int customer_count = 0; // 顾客数量
int service_time = 0; // 服务时间
int id = 0; // 顾客编号
// 模拟10个小时的服务时间
for (int i = 0; i < 10; i++) {
// 每小时到达的顾客数量为1~5个之间的随机数
int arrival_count = rand() % 5 + 1;
for (int j = 0; j < arrival_count; j++) {
Customer c;
c.id = ++id;
c.arrive_time = total_time;
c.service_time = rand() % 5 + 1;
enqueue(&queue, c);
printf("Customer %d arrives at %d.\n", c.id, c.arrive_time);
}
if (!is_empty(&queue)) {
Customer c = dequeue(&queue);
service_time = c.service_time;
wait_time = total_time - c.arrive_time;
printf("Customer %d starts service at %d, waiting time is %d.\n", c.id, total_time, wait_time);
total_time += service_time;
customer_count++;
}
else {
printf("No customers at %d.\n", total_time);
}
}
printf("Total customers: %d\n", customer_count);
printf("Average waiting time: %.2f\n", (float)wait_time / customer_count);
return 0;
}
```
上述代码中,定义了一个顾客结构体和一个队列结构体,顾客结构体包含顾客的编号、到达时间和服务时间,队列结构体包含一个顾客数组和队头、队尾指针。
在主函数中,先初始化队列,然后模拟10个小时的服务时间,每小时到达的顾客数量为1~5个之间的随机数,每个顾客的服务时间也是1~5个之间的随机数。如果队列不为空,则出队一个顾客进行服务,服务时间为该顾客的服务时间,等待时间为服务开始时间减去到达时间,总时间加上服务时间,统计顾客数量和平均等待时间。
注意,此代码为简单模型,没有考虑到多种情况,如服务时间不足、队列满员等,仅供参考。