编写C程序,模拟“最短作业优先(SJF)” 调度算法,编写以下函数,计算平均带权周转时间并返回,空函数: double sjf_weighted_time (int *arrival_time, int *run_time, int num){ },主函数int job_num = 5;//job number int arrival_time[] = { 0, 1, 2, 5, 7 };//arrival time int run_time[] = { 8, 2, 3, 10, 9 };//run time //SJF double result = sjf_weighted_time(arrival_time, run_time, job_num); printf("%.2lf", result);
时间: 2024-02-25 16:56:08 浏览: 74
以下是实现最短作业优先(SJF)算法计算平均带权周转时间的 C 语言代码:
```c
#include <stdio.h>
double sjf_weighted_time(int *arrival_time, int *run_time, int num) {
double completion_time[num], turn_around_time[num], waiting_time[num], total_waiting_time = 0, total_turn_around_time = 0;
// 完成时间初始化为0
for (int i = 0; i < num; i++) {
completion_time[i] = 0;
}
// 按到达时间排序作业
for (int i = 0; i < num; i++) {
for (int j = i + 1; j < num; j++) {
if (arrival_time[i] > arrival_time[j]) {
int temp = arrival_time[i];
arrival_time[i] = arrival_time[j];
arrival_time[j] = temp;
temp = run_time[i];
run_time[i] = run_time[j];
run_time[j] = temp;
}
}
}
// 计算完成时间和周转时间
for (int i = 0; i < num; i++) {
if (i == 0) {
completion_time[i] = arrival_time[i] + run_time[i];
} else {
if (arrival_time[i] > completion_time[i - 1]) {
completion_time[i] = arrival_time[i] + run_time[i];
} else {
completion_time[i] = completion_time[i - 1] + run_time[i];
}
}
turn_around_time[i] = completion_time[i] - arrival_time[i];
}
// 计算带权周转时间和平均带权周转时间
for (int i = 0; i < num; i++) {
waiting_time[i] = turn_around_time[i] - run_time[i];
total_waiting_time += waiting_time[i];
total_turn_around_time += turn_around_time[i];
}
return total_turn_around_time / num / run_time[0];
}
int main() {
int job_num = 5;
int arrival_time[] = {0, 1, 2, 5, 7};
int run_time[] = {8, 2, 3, 10, 9};
double result = sjf_weighted_time(arrival_time, run_time, job_num);
printf("平均带权周转时间为:%.2lf", result);
return 0;
}
```
该程序实现了最短作业优先(SJF)算法计算平均带权周转时间的功能。主函数中定义了作业数、到达时间数组和运行时间数组,然后调用 `sjf_weighted_time` 函数计算平均带权周转时间,并输出结果。
阅读全文