自己闲的蛋疼,把磁盘调度算法用C跟C++模拟了一下,不知道有没有bug,欢迎提出建议~
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = 100;
int n, now, s, sum, nnow, everage, p[maxn], b[maxn], sp[maxn], lenp[maxn];
//显示结果
void show()
{
sum = 0;
cout <<" 被访问的下一磁道号 移动距离(磁道数)\n";
for(int i = 0;i < n; ++i)
{
printf(" %3d %3d\n", sp[i], lenp[i]);
sum += lenp[i];
}
cout <<" 平均寻道长度: "<<(double)sum/n <<"\n";
}
//先来先服务
void FCFS()
{
for(int i = 0;i < n; ++i)
{
sp[i] = p[i];
if(i) lenp[i] = abs(sp[i-1] - sp[i]);
else lenp[i] = abs(now - sp[i]);
}
}
//最短寻道优先
void SSTF()
{
nnow = now;
int fl[maxn] = {0};
for(int i = 0;i < n; ++i)
{
int minx = 999999, pp;
for(int j = 0;j < n; ++j)
{
if(!fl[j] && abs(nnow - p[j]) < minx)
{
minx = abs(nnow - p[j]);
pp = j;
}
}
sp[i] = p[pp];
lenp[i] = minx;
nnow = p[pp];
fl[pp] = 1;
}
}
//扫描算法
bool cmp(int a, int b)
{
return a > b;
}
void SCAN()
{
nnow = now;
int aa[maxn], bb[maxn], ak = 0, bk = 0;
for(int i = 0;i < n; ++i)
{
if(p[i] < nnow) aa[ak++] = p[i];
else bb[bk++] = p[i];
}
sort(aa, aa+ak,cmp);
sort(bb, bb+bk);
int i = 0;
for(int j = 0;j < bk; ++j)
{
sp[i] = bb[j];
lenp[i++] = bb[j] - nnow;
nnow = bb[j];
}
for(int j = 0;j < ak; ++j)
{
sp[i] = aa[j];
lenp[i++] = nnow - aa[j];
nnow = aa[j];
}
}
//循环扫描算法
void CSCAN()
{
nnow = now;
int aa[maxn], bb[maxn], ak = 0, bk = 0;
for(int i = 0;i < n; ++i)
{
if(p[i] < nnow) aa[ak++] = p[i];
else bb[bk++] = p[i];
}
sort(aa, aa+ak);
sort(bb, bb+bk);
int i = 0;
for(int j = 0;j < bk; ++j)
{
sp[i] = bb[j];
lenp[i++] = bb[j] - nnow;
nnow = bb[j];
}
for(int j = 0;j < ak; ++j)
{
sp[i] = aa[j];
lenp[i++] = abs(aa[j] - nnow);
nnow = aa[j];
}
}
int main()
{
xbegin:
cout<<"请输入被访问的总磁道数: ";
cin >> n;
if(n <= 0 || n > 100)
{
cout <<"输入不合法,请重新输入!\n";
goto xbegin;
}
nowCD:
cout <<"请输入当前磁道: ";
cin >> now;
if(now < 0)
{
cout <<"磁道不存在,请重新输入!";
goto nowCD;
}
pCD:
cout <<"请按顺序输入所有需要访问的磁道:";
for(int i = 0;i < n; ++i) cin >> p[i];
for(int i = 0;i < n; ++i)
{
b[i] = p[i];
if(p[i] < 0)
{
cout <<"输入中有不存在的磁道,请重新输入!\n";
goto pCD;
}
}
serve:
cout <<" 1、先来先服务算法(FCFS)\n";
cout <<" 2、最短寻道优先算法(SSTF)\n";
cout <<" 3、扫描算法(SCAN)\n";
cout <<" 4、循环扫描算法(CSCAN)\n";
cout <<"请输入所用磁盘调度的算法: ";
cin >> s;
if(s < 1 || s > 4)
{
cout <<"输入有误,请重新输入!\n";
goto serve;
}
work:
for(int i = 0;i < n; ++i) p[i] = b[i];
if(s == 1) FCFS();
else if(s == 2) SSTF();
else if(s == 3) SCAN();
else CSCAN();
show();
xend:
char ch;
cout <<"重新选择算法或重新输入数据?(输入Y选择算法,输入y重新输入数据): ";
cin >> ch;
if(ch == 'Y') goto serve;
else if(ch == 'y') goto xbegin;
else cout <<"程序结束,谢谢使用!\n";
return 0;
}