请帮我用c语言依次实现操作系统中磁盘调度算法FCFS算法和SSTF算法和SCAN算法和CSCAN算法。
时间: 2023-11-25 08:51:20 浏览: 97
以下是C语言实现FCFS、SSTF、SCAN、CSCAN四种磁盘调度算法的代码:
1. FCFS算法
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n, i, j, head, sum = 0;
printf("请输入磁盘请求数量:");
scanf("%d", &n);
int a[n];
printf("请输入磁盘请求序列:");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("请输入磁头初始位置:");
scanf("%d", &head);
for(i = 0; i < n; i++)
{
sum += abs(head - a[i]);
head = a[i];
}
printf("磁头移动距离为:%d\n", sum);
return 0;
}
```
2. SSTF算法
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n, i, j, head, sum = 0, min, index;
printf("请输入磁盘请求数量:");
scanf("%d", &n);
int a[n], b[n];
printf("请输入磁盘请求序列:");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
b[i] = 0;
}
printf("请输入磁头初始位置:");
scanf("%d", &head);
for(i = 0; i < n; i++)
{
min = 1000000;
for(j = 0; j < n; j++)
{
if(b[j] == 0 && abs(head - a[j]) < min)
{
min = abs(head - a[j]);
index = j;
}
}
b[index] = 1;
sum += min;
head = a[index];
}
printf("磁头移动距离为:%d\n", sum);
return 0;
}
```
3. SCAN算法
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n, i, j, head, sum = 0, min, index, flag = 0;
printf("请输入磁盘请求数量:");
scanf("%d", &n);
int a[n], b[n];
printf("请输入磁盘请求序列:");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
b[i] = 0;
}
printf("请输入磁头初始位置:");
scanf("%d", &head);
for(i = 0; i < n; i++)
{
min = 1000000;
for(j = 0; j < n; j++)
{
if(b[j] == 0 && abs(head - a[j]) < min)
{
if(flag == 0 && a[j] >= head)
{
min = abs(head - a[j]);
index = j;
}
else if(flag == 1 && a[j] <= head)
{
min = abs(head - a[j]);
index = j;
}
else if(flag == 0 && a[j] < head)
{
min = abs(head - a[j]);
index = j;
}
else if(flag == 1 && a[j] > head)
{
min = abs(head - a[j]);
index = j;
}
}
}
b[index] = 1;
sum += min;
head = a[index];
if(flag == 0 && head == 0)
{
flag = 1;
}
else if(flag == 1 && head == 199)
{
flag = 0;
}
}
printf("磁头移动距离为:%d\n", sum);
return 0;
}
```
4. CSCAN算法
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n, i, j, head, sum = 0, min, index, flag = 0;
printf("请输入磁盘请求数量:");
scanf("%d", &n);
int a[n], b[n];
printf("请输入磁盘请求序列:");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
b[i] = 0;
}
printf("请输入磁头初始位置:");
scanf("%d", &head);
for(i = 0; i < n; i++)
{
min = 1000000;
for(j = 0; j < n; j++)
{
if(b[j] == 0 && abs(head - a[j]) < min)
{
if(flag == 0 && a[j] >= head)
{
min = abs(head - a[j]);
index = j;
}
else if(flag == 1 && a[j] <= head)
{
min = abs(head - a[j]);
index = j;
}
}
}
b[index] = 1;
sum += min;
head = a[index];
if(flag == 0 && head == 199)
{
flag = 1;
sum += 199;
head = 0;
}
else if(flag == 1 && head == 0)
{
flag = 0;
sum += 199;
head = 199;
}
}
printf("磁头移动距离为:%d\n", sum);
return 0;
}
```
阅读全文