用c++编写采用“最高优先数优先”调度算法对五个进程进行调度的代码
时间: 2024-05-08 14:15:55 浏览: 92
以下是使用C语言编写的基于“最高优先数优先”调度算法的代码,其中有五个进程:
```c
#include <stdio.h>
#define MAX_PROCESS 5
int main() {
int burst_time[MAX_PROCESS], priority[MAX_PROCESS], turnaround_time[MAX_PROCESS], waiting_time[MAX_PROCESS], completion_time[MAX_PROCESS];
int i, j, highest_priority_index, total_waiting_time = 0, total_turnaround_time = 0;
// 输入每个进程的执行时间和优先级
printf("Enter burst time and priority for each process:\n");
for (i = 0; i < MAX_PROCESS; i++) {
printf("Process %d: ", i + 1);
scanf("%d %d", &burst_time[i], &priority[i]);
}
// 按照优先级对进程进行排序
for (i = 0; i < MAX_PROCESS - 1; i++) {
highest_priority_index = i;
for (j = i + 1; j < MAX_PROCESS; j++) {
if (priority[j] > priority[highest_priority_index]) {
highest_priority_index = j;
}
}
// 将优先级最高的进程移到最前面
if (highest_priority_index != i) {
int temp_burst_time = burst_time[i], temp_priority = priority[i];
burst_time[i] = burst_time[highest_priority_index];
priority[i] = priority[highest_priority_index];
burst_time[highest_priority_index] = temp_burst_time;
priority[highest_priority_index] = temp_priority;
}
}
// 计算每个进程的完成时间、周转时间和等待时间
completion_time[0] = burst_time[0];
turnaround_time[0] = completion_time[0];
waiting_time[0] = 0;
for (i = 1; i < MAX_PROCESS; i++) {
completion_time[i] = completion_time[i - 1] + burst_time[i];
turnaround_time[i] = completion_time[i];
waiting_time[i] = completion_time[i - 1];
total_waiting_time += waiting_time[i];
total_turnaround_time += turnaround_time[i];
}
// 输出每个进程的完成时间、周转时间和等待时间
printf("\nProcess\tBurst Time\tPriority\tCompletion Time\tTurnaround Time\tWaiting Time\n");
for (i = 0; i < MAX_PROCESS; i++) {
printf("%d\t\t%d\t\t%d\t\t%d\t\t\t%d\t\t\t%d\n", i + 1, burst_time[i], priority[i], completion_time[i], turnaround_time[i], waiting_time[i]);
}
// 输出平均周转时间和平均等待时间
printf("\nAverage Turnaround Time: %.2f\n", (float) total_turnaround_time / MAX_PROCESS);
printf("Average Waiting Time: %.2f\n", (float) total_waiting_time / MAX_PROCESS);
return 0;
}
```
阅读全文