我正在编码以使用最短剩余时间优先算法(SRTF)计算进程的平均等待时间和周转时间。
我想将结果打印成格式如下所示的表格。
Enter the number of processess:4
Enter the process name, CPU Burst Time, Arrival Time row wise:
1 3 0
2 6 1
3 4 4
4 2 6
Process CPU AT Finish TT WT
1 3 0 3 3 0
2 6 1 15 14 9
3 4 4 5 1 1
4 2 6 5 -1 3
The average turnaround time is: 4.000000
The average waiting time is: 3.000000
此处AT =到达时间,TT =周转时间,WT =等待时间。但是出现一些错误,因为过程3和4的完成时间是不可能的。这是我的代码:
#include<stdio.h>
#include<stdlib.h>
int **a;
int return_min(int upto, int n)
{
int min=1000, idx =-1;
for(int i=0; i<n; i++)
{
if(a[i][1]!=-1 && a[i][2]<=upto && min>a[i][1])
{
min=a[i][1];
idx = i;
}
}
return idx;
}
void main()
{
int n,i,j,time=0, idx,total_tt=0, total_wt=0;
float avg_tt, avg_wt;
printf("Enter the number of processess:");
scanf("%d",&n);
a=(int **)malloc(sizeof(int *)*n);
printf("\nEnter the process name, CPU Burst Time, Arrival Time row wise:\n");
for(i=0;i<n;i++)
{
*(a+i)=(int *)malloc(sizeof(int)*7);
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
a[i][6]=a[i][1];
}
while((idx=return_min(time,n)) != -1)
{
a[idx][1]--;
if(a[idx][1] == 0)
a[idx][1]--;
time++;
for(int i=0; i<n; i++)
{
if(a[i][1]!=-1 && i!=idx && a[i][2]<=time)
a[i][5]++;
}
}
printf("\n\tProcess\tCPU\tAT\tFinish\tTT\tWT\n");
for(i=0;i<n;i++)
{
a[i][1]=a[i][6];
a[i][3]=a[i][5]+a[i][1];
a[i][4]=a[i][3]-a[i][2];
for(j=0;j<6;j++)
{
printf("\t%d",a[i][j]);
}
printf("\n");
}
for(i=0;i<n;i++)
total_tt+=a[i][4];
avg_tt = total_tt/n;
printf("\nThe average turnaround time is: %f", avg_tt);
for(i=0;i<n;i++)
total_wt+=a[i][5];
avg_wt = total_wt/n;
printf("\nThe average waiting time is: %f\n", avg_wt);
}
我做的所有错误是什么?请指正。
答案 0 :(得分:3)
请注意:
Turnaround Time = Finish Time- Arrival Time
Waiting Time = Turnaround Time - CPU Burst Time
因此,
您应该在main函数的第二个for循环中更改代码:
a[i][4]=a[i][5]+a[i][1];
a[i][3]=a[i][4]+a[i][2];
最终它会正常运作。