C中的FOR循环,条件部分

问题描述 投票:0回答:6

小问题只是为了澄清。

在 ZX-Spectrum BASIC 编译器中有 FOR TO STEP NEXT 循环,其中 TO 是无条件的:

10 FOR i=1 TO 5 STEP 1

我在 C 中尝试过类似的做法

for (i=1; i==5; i++); 

当然循环不起作用(==在这里永远不会为真)...所以问题是:

在 C FOR 循环中,我们应该 always 使用条件来停止循环(我的意思是 FOR 语句括号中的条件),例如 FOR (i=0; i<6; i++);

c basic zxspectrum
6个回答
4
投票

正确翻译:

for i = 1 to 5 step 1

会是:

for (i = 1; i <= 5, i++)

换句话说,循环运行五次,控制变量设置为

1
2
3
4
5
连续迭代。

您可以使用其他变体,例如不同的条件运算符和不同的终止值,但显示的最匹配 BASIC 变体,同时在您的步骤可能不止一个的情况下仍然保护您(例如

for i = 1 to 4 step 2
)。

请记住,C 数组是从 0 开始的,因此,如果您使用

i
访问数组,它需要从
0
n-1
,而不是
1
n
。如果您只想将该变量用于其他目的(例如打印出从一到五的数字),
1..n
变体就可以了。


1
投票

你可以使用

for (i = 1; i != 6; i++); 

但是最好使用

i = 0 ... i < 5
,以防您在循环内部更改
i
。它还可以传达您做得更好的地方。


1
投票

没有任何限制,你必须在for循环中使用条件语句..
您还可以在 for 循环体中使用此条件语句,如下所示......

for(int i=0;;i++)
{
      if(i>=5)
      {
         break;// to break the loop
      }
}

如果您不在 for 循环或 for 循环体中使用条件语句 at,则循环进入无限状态,如下所示....

for(int i=0;;i++)
{
    //any statements
}

因为在 for 循环中,所有三个部分都是可选的(初始化、条件、incri/decri)

int i=0
for(;;)
{
      if(i>=5)
      {
           //any statements
      }

      i++
}

0
投票

循环条件不是必需的,你可以像这样写循环

for(int i=0;;i++)
{
//body
}

但请注意,循环体应包含一些 break 语句,否则循环将无限期执行


0
投票

你的代码有两个问题,你不应该使用;在你的循环头之后,你可以使用 < or <= in your condition part like this:

for(int i=1; i<=5; i++){}

所以它应该是一个条件但你不必使用不等式你可以使用任何其他条件但它应该完成一次


0
投票

是的,条件必须有“<"or ">”或“>=”或“<=" as we need to apply a limit to the loop. when you use "==" the loop will test if the number is equal to 5 or not and of course 0 is not equal to 5 and hence the loop will be terminated. where as when you use "<" the loop will check if the value of "i" is less than the 5 or not. Also you have put ";" after the for loop statement which is incorrect since, any of the statement inside the for loop braces wont be executed.

© www.soinside.com 2019 - 2024. All rights reserved.