Files
CPP/计算机组成原理实验代码/OPT.cpp
2023-05-12 00:34:15 +08:00

109 lines
2.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <iostream>
using namespace std;
int number=0;
int Pyblock=0;
int opt(int a[])
{
int i, j, zero = 0, one = 0, two = 0, q = 0;
int b[Pyblock];
for (i = 0; i < Pyblock; i++)
{
b[i] =-1; //空为-1
}
for (i = 0; i < number; i++)
{
if (i < 3)
{
q++;
for (j = 0; j < Pyblock; j++)
{
if (b[j] == -1)
{
b[j] = a[i];
break;
}
}
}
else
{
if (b[0] != a[i])
{
if (b[1] != a[i])
{
if(b[2] != a[i]){
q++;
for (int t = i + 1; t < number; t++)
{
if (b[0] == a[t])
zero = 1;
else if (b[1] == a[t])
one = 1;
else if (b[2] == a[t])
two = 1;
if (zero == 1 && one == 1 && two == 0)
{
b[2] = a[i];
break;
}
else if (zero == 1 && one == 0 && two == 1)
{
b[1] = a[i];
break;
}
else if (zero == 0 && one == 1 && two == 1)
{
b[0] = a[i];
break;
}
}
}
}
}
}
for (int f = 0; f < Pyblock; f++)
{
printf("%d\t", b[f]);
}
printf("\n");
zero = 0;
one = 0;
two = 0;
}
return q;
}
int main()
{
int o;
while(1)
{
printf("请输入分配的物理块的个数:\n");
scanf("%d",&Pyblock);
printf("\n");
break;
}
while(1)
{
printf("请输入页面序列个数:\n");
scanf("%d",&number);
printf("\n");
break;
}
int a[number];
printf("请依次输入页面序列:\n");
for (int i = 0; i < number; i++)
{
cin>>a[i];
}
printf("opt页面置换算法\n");
o = opt(a);
printf("缺页%d次置换%d次, 缺页率:%.2f%% .\n\n\n", o, o - Pyblock,((double)o/number)*100);
return 0;
}
//4 3 2 1 4 3 5 4 3 2 1 5