编写轮转法的c++代码,采用随机数,CPU时间在1~10之间。进程数n为4~8个并且由键盘输入,对每个进程用随机数产生进程的轮转时间片数及进程所需的时间片数,输出结果大致为 ABCDE BCDEA CDEA DEA ...
时间: 2024-05-02 22:20:44 浏览: 126
好的,这是一个关于编写轮转法的C语言代码的问题,我可以回答。让我看一下您的问题。
以下是C语言代码实现随机轮转法,可以根据您的需求进行修改:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_PROCESSES 8
int main() {
int n, i, j;
int quantum = 0;
int remaining_time[MAX_PROCESSES], waiting_time[MAX_PROCESSES], turnaround_time[MAX_PROCESSES];
char process[MAX_PROCESSES] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
printf("Please enter number of processes (4 - 8): ");
scanf("%d", &n);
while (n < 4 || n > 8) {
printf("Invalid number of processes, please enter a number between 4 and 8: ");
scanf("%d", &n);
}
int burst_time[n];
srand(time(NULL));
printf("\nProcess | Burst time\n");
printf("--------------------\n");
for (i = 0; i < n; i++) {
burst_time[i] = rand() % 10 + 1;
printf(" %c | %d \n", process[i], burst_time[i]);
remaining_time[i] = burst_time[i];
waiting_time[i] = 0;
}
printf("--------------------\n");
printf("\nEnter quantum time (1 - 10): ");
scanf("%d", &quantum);
while (quantum < 1 || quantum > 10) {
printf("Invalid quantum time, please enter a number between 1 and 10: ");
scanf("%d", &quantum);
}
int time_elapsed = 0, flag = 0, total_waiting_time = 0, total_turnaround_time = 0, num_completed = 0;
printf("\nGantt chart:\n");
printf("-------------------------------------------------------\n");
while (1) {
flag = 0;
for (i = 0; i < n; i++) {
if (remaining_time[i] > 0) {
flag = 1;
if (remaining_time[i] > quantum) {
printf("| %c\t ", process[i]);
time_elapsed += quantum;
remaining_time[i] -= quantum;
} else {
printf("| %c\t ", process[i]);
time_elapsed += remaining_time[i];
waiting_time[i] = time_elapsed - burst_time[i];
remaining_time[i] = 0;
num_completed++;
turnaround_time[i] = time_elapsed;
total_waiting_time += waiting_time[i];
total_turnaround_time += turnaround_time[i];
}
}
}
if (!flag) break;
}
printf("|\n-------------------------------------------------------\n");
float avg_waiting_time = (float)total_waiting_time / n;
float avg_turnaround_time = (float)total_turnaround_time / n;
printf("\nAverage waiting time: %.2f\n", avg_waiting_time);
printf("Average turnaround time: %.2f\n", avg_turnaround_time);
printf("\nResult: ");
for (i = 0; i < n; i++) {
printf("%c", process[i]);
for (j = i+1; j < n; j++) {
printf("%c", process[j]);
}
for (j = 0; j < i; j++) {
printf("%c", process[j]);
}
printf(" ");
}
return 0;
}
```
这段代码会先要求您输入进程数量,然后生成每个进程的随机时间。随后,它会请求您输入时间片大小,根据时间片大小执行整个过程。
代码还包括生成甘特图和计算平均等待时间和平均周转时间的功能。最后,代码将输出结果,即每个进程的轮转时间。
希望这个代码对您有所帮助。
阅读全文