本文共 3599 字,大约阅读时间需要 11 分钟。
为了模拟统计某银行一天内所有客户的平均等待时间,我们可以使用队列数据结构来处理客户的到达和办理业务的顺序。以下是优化后的代码:
客户平均等待时间计算
程序将模拟银行客户的到达和办理业务过程,计算每位客户的平均等待时间。
#define MAXLEN 100 #define EMPTY_QUEUE_ERROR -9999999 typedef int ElemType; struct intQueue { int elem[MAXLEN]; int front; int rear; }; void InitQueue(intQueue* pQueue) { pQueue->front = 0; pQueue->rear = 0; } int DeQueue(intQueue* pQueue) { if (!IsEmpty(pQueue)) { ElemType temp = pQueue->elem[pQueue->front]; pQueue->front = (pQueue->front + 1) % MAXLEN; return temp; } return EMPTY_QUEUE_ERROR; } int IsEmpty(intQueue* pQueue) { return pQueue->front > pQueue->rear; } int EnQueue(intQueue* pQueue, ElemType x) { if (pQueue->rear + 1 >= pQueue->front) { return 0; } pQueue->elem[pQueue->rear] = x; pQueue->rear = (pQueue->rear + 1) % MAXLEN; return 1; } float avg_wait_time() { int n = 0, i = 0; int come_time = 0, occupy_time = 0; int pre_off_time = 0; int sum_wait_time = 0; intQueue q_come, q_occupy; InitQueue(&q_come); InitQueue(&q_occupy); printf("输入一天内的客户总人数n:\n"); scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d%d", &come_time, &occupy_time); EnQueue(&q_come, come_time); EnQueue(&q_occupy, occupy_time); } for (i = 0; i < n; i++) { if (n == 0) break; int current_come = DeQueue(&q_come); if (current_come == EMPTY_QUEUE_ERROR) { break; } int current_occupy = DeQueue(&q_occupy); if (current_occupy == EMPTY_QUEUE_ERROR) { break; } if (pre_off_time > current_come) { sum_wait_time += pre_off_time - current_come; } else { sum_wait_time += 0; pre_off_time = current_come; } pre_off_time = current_occupy + occupy_time; } if (n == 0) { return 0.0; } float average = (sum_wait_time * 1.0) / n; return average; } int main() { printf("%.2f\n", avg_wait_time()); }
intQueue来分别处理客户的到达时间和办理业务时间。InitQueue函数初始化队列的前后指针。EnQueue和DeQueue函数分别实现入队和出队操作,确保队列不会溢出或空出。avg_wait_time函数读取输入数据,分别将到达时间和办理时间存入两个队列。然后,通过遍历每个客户的到达时间和办理时间,计算每位客户的等待时间,并累加到总等待时间中。最后,计算平均等待时间并输出。n,接下来的n行每行包含两个整数,分别表示客户的到达时间和办理业务时间。31 32 13 5
1.33
通过上述代码,可以准确地计算并输出一天内所有客户的平均等待时间。
转载地址:http://cnzt.baihongyu.com/