循环复制循环

发布于 2025-01-25 16:56:37 字数 342 浏览 3 评论 0原文

嗨,我试图执行磁盘调度算法(C-SCAN)。我有一个有效的if语句循环,但是我试图将其更改为ther loop或其他选项以删除断路语句。

  for(i=0;i<n;i++)
    {
        if(initial<RQ[i])
        {
            index=i;
            break;
        }
    }

while ( initial>RQ[i] ) 
{ 
    index =i;

    i++;     
}

以上循环是我试图复制的内容,如我的时循环中所示。但是,它的工作方式并不相同。 任何帮助将不胜感激

Hi im trying to do a disk scheduling algorithm (C-SCAN).I have a for loop with an if statement that works, however im trying to change it to a while loop or another option to remove the break statement.

  for(i=0;i<n;i++)
    {
        if(initial<RQ[i])
        {
            index=i;
            break;
        }
    }

while ( initial>RQ[i] ) 
{ 
    index =i;

    i++;     
}

The above for loop is what im trying to replicate as seen in my while loop. however it is not working the same way.
any help will be much appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

海之角 2025-02-01 16:56:38

表格循环的

for (initialization; condition; repetition) {
    // body code
}

等同于:

initialization;
while (condition) {
    // body code
    repetition;
}

因此,您的循环将被重写为:

i = 0;
while (i < n) {
    if (initial < RQ[i]) {
        index = i;
        break;
    }
    i++;
}

A for loop of the form

for (initialization; condition; repetition) {
    // body code
}

is equivalent to:

initialization;
while (condition) {
    // body code
    repetition;
}

So your loop would be rewritten as:

i = 0;
while (i < n) {
    if (initial < RQ[i]) {
        index = i;
        break;
    }
    i++;
}
梦里的微风 2025-02-01 16:56:38

删除break语句的一种可能性是引入一个附加的标志变量,该变量应在应终止循环时设置。

#include <stdbool.h>

[...]

bool terminate = false;

for( i=0; i<n && !terminate ; i++ )
{
    if(initial<RQ[i])
    {
        index=i;
        terminate = true;
    }
}

但是,我个人认为使用break语句更好。

One possibility of removing the break statement would be to introduce an additional flag variable which gets set when the loop should be terminated.

#include <stdbool.h>

[...]

bool terminate = false;

for( i=0; i<n && !terminate ; i++ )
{
    if(initial<RQ[i])
    {
        index=i;
        terminate = true;
    }
}

However, I personally consider it better to use a break statement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文