先来先服务算法用c++语言
时间: 2023-05-28 16:02:19 浏览: 38
以下是一个示例程序,使用C语言实现了先来先服务算法:
#include<stdio.h>
#include<stdlib.h>
struct Process {
int id;
int arrivalTime;
int burstTime;
int completionTime;
int turnaroundTime;
int waitingTime;
};
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
struct Process p[n];
printf("Enter the arrival time and burst time of each process:\n");
for(int i=0; i<n; i++) {
printf("Process %d:", i+1);
p[i].id = i+1;
scanf("%d %d", &p[i].arrivalTime, &p[i].burstTime);
}
// sort the processes based on arrival time
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
if(p[i].arrivalTime > p[j].arrivalTime) {
struct Process temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
// calculate completion time, turnaround time and waiting time
int currentTime = 0;
for(int i=0; i<n; i++) {
if(currentTime < p[i].arrivalTime) {
currentTime = p[i].arrivalTime;
}
p[i].completionTime = currentTime + p[i].burstTime;
p[i].turnaroundTime = p[i].completionTime - p[i].arrivalTime;
p[i].waitingTime = p[i].turnaroundTime - p[i].burstTime;
currentTime = p[i].completionTime;
}
// calculate average turnaround time and waiting time
float avgTurnaroundTime = 0, avgWaitingTime = 0;
for(int i=0; i<n; i++) {
avgTurnaroundTime += p[i].turnaroundTime;
avgWaitingTime += p[i].waitingTime;
}
avgTurnaroundTime /= n;
avgWaitingTime /= n;
// print the results
printf("Process\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\tWaiting Time\n");
for(int i=0; i<n; i++) {
printf("%d\t%d\t\t%d\t\t%d\t\t%d\t\t\t%d\n", p[i].id, p[i].arrivalTime, p[i].burstTime, p[i].completionTime, p[i].turnaroundTime, p[i].waitingTime);
}
printf("Average turnaround time: %.2f\n", avgTurnaroundTime);
printf("Average waiting time: %.2f\n", avgWaitingTime);
return 0;
}
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)