C 页面替换算法代码中的逻辑错误(bug)
在下面的优化页面替换算法代码中,如果我输入整数输入,则first for循环下的scanf不会在'n'值处停止。如果输入是重复的,它工作得很好 例如:如果n的值是7,而pageinput是1 代码运行良好 但是如果页面输入是12341 它从不停止输入 我甚至像我一样在for循环中尝试了显式声明 例:如果n的值是7,pagein-put是1,那么代码工作正常,但是如果pageinput是1,那么它永远不会停止输入 对我来说,它不是无止境地获取输入,而是永远循环,因为:C 页面替换算法代码中的逻辑错误(bug),c,debugging,operating-system,scanf,C,Debugging,Operating System,Scanf,在下面的优化页面替换算法代码中,如果我输入整数输入,则first for循环下的scanf不会在'n'值处停止。如果输入是重复的,它工作得很好 例如:如果n的值是7,而pageinput是1 代码运行良好 但是如果页面输入是12341 它从不停止输入 我甚至像我一样在for循环中尝试了显式声明 例:如果n的值是7,pagein-put是1,那么代码工作正常,但是如果pageinput是1,那么它永远不会停止输入 对我来说,它不是无止境地获取输入,而是永远循环,因为: while(temp_j&l
while(temp_j<k)
{
if(page[temp_i]==frame[temp_j])
{
position[temp_j]=temp_i;
temp_j++;
}
//temp_i++;
}
您不会进入while forever案例,但是
pi@raspberrypi:/tmp $ ./a.out
Enter the number of pages
7
Enter the number of frames
1
Enter the page sequence
1 2 3 4 5 6 7
你进去吧
总是做
temp_j++似乎更合乎逻辑代码>像这样:
while(temp_i<n)
{
temp_j=0;
while(temp_j<k)
{
if(page[temp_i]==frame[temp_j])
{
position[temp_j]=temp_i;
}
temp_j++;
}
temp_i++;
}
我从两个方面找到了答案。
一个由@bruno在原始答案中提出
另一个如下
通过使用for循环而不是while
if(j==k)
{
temp_i=i;temp_j=0;
for(l=0;l<k;l++)
position[l]=MAX;
for(temp_i=i;temp_i<n;temp_i++)
{
for(temp_j=0;temp_j<k;temp_j++)
{
if(page[temp_i]==frame[temp_j])
{
position[temp_j]=temp_i;
}
//temp_i++;
}
}
maximum=maxim(position,k);
frame[maximum]=page[i];
count+=1;
}
if(j==k)
{
温度i=i;温度j=0;
对于(l=0;lTry)在您的scanf下面输入以下命令:fflush(stdin);
。应该是这样的:scanf(%d),&page[i]);fflush(stdin);
您可以创建一个吗?您确定错误不在其他地方吗?您的意思是在之前重置temp\u j=0;
,而(temp\u jAddprintf(“i/O完成”);fflush(stdout)
在输入循环之后。在OK和failure两种情况下,屏幕上都会出现这种情况吗?我怀疑您在其他地方有问题。如果问题在输入中,您不需要显示大量代码来演示问题。(顺便说一句,重复int
并没有害处-不要用一个int
分散三行变量定义)@EsdrasXavier:建议使用fflush(stdin)
。有关详细信息,请参阅,但它仅在Windows系统上可靠工作,不是通用解决方案。它甚至不是特别理想的解决方案;它会阻止我在一行上输入12341
——这会很烦人,因为它会丢弃我仔细键入的数据。如果我取消对temp_I++acc的注释与else合并,并移除其下方的temp_i++。输入问题很严重,但它将出现分段错误(内核转储)@SatyamSrivastava可能是因为temp_i++
变得太大,您超出了页面,您还需要检查temp_i
值,同时检查我在原始代码中所做的操作,到那时,正如您所指出的,这给了我一个输入问题。有什么建议吗?
while(temp_i<n)
{
temp_j=0;
while(temp_j<k)
{
if(page[temp_i]==frame[temp_j])
{
position[temp_j]=temp_i;
}
temp_j++;
}
temp_i++;
}
Enter the number of pages
12
Enter the number of frames
3
Enter the page sequence
1 2 3 4 1 2 5 1 2 3 4 5
The final frames status is:
523The number of page fault is 9
The hit ratio is 0.750000
if(j==k)
{
temp_i=i;temp_j=0;
for(l=0;l<k;l++)
position[l]=MAX;
for(temp_i=i;temp_i<n;temp_i++)
{
for(temp_j=0;temp_j<k;temp_j++)
{
if(page[temp_i]==frame[temp_j])
{
position[temp_j]=temp_i;
}
//temp_i++;
}
}
maximum=maxim(position,k);
frame[maximum]=page[i];
count+=1;
}