有关for循环和while循环的问题 [英] question about for loop and while loop
本文介绍了有关for循环和while循环的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void main()
int n=1;
for(;n<5;)
printf("%d",n);
n++;
}
1上面的for循环可以类似于while循环吗?当我们在循环之前初始化控制变量并在循环主体中递增/递减时
1 can above for loop is similar to while loop? when we initialize control variable before the loop and increment/decrement in the body of the loop
推荐答案
不太正确:您的版本永远不会停止打印-您需要"{"和}"包含循环内容,否则只会循环执行第一条语句.
但是:
Not quite: Your version would never stop printing - you need "{" and "}" to contain the loop contents, or the first statement only will be looped on.
But:
int i;
for (i = 0; i < 5; i++)
printf("%d",i);
等同于:
Is the same as:
int i=0;
while (i < 5)
{
printf("%d",i);
i++;
}
或:
or:
int i=0;
for (;i < 5;)
{
printf("%d",i);
i++;
}
但是您不应该真正使用最后一个示例.
顺便说一句:一个好主意是,当您开始避免我一开始提到的那种问题时,始终在if条件循环中使用大括号!
But you shouldn''t really use the final example.
BTW: It is a good idea to always use curly brackets in a loop of if condition when you are starting to avoid just the kind of problem I mentions at the start!
这篇关于有关for循环和while循环的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文