简单的 for 循环不起作用
我刚刚开始学习编程。我正在研究循环但是 该程序无法按预期工作。我想在什么时候打破循环 $a
等于 3
,因此我得到输出 1 2
但我得到 3
作为输出:(
for($a=0;$a<10;++$a)
{
if($a==3)
break
print"$a ";
}
请帮忙。
I've just started learning programming. I'm studying for loops but
this program does not work as expected. I want to break the loop when$a
is equal to 3
so that I get the output 1 2
but I get 3
as output :(
for($a=0;$a<10;++$a)
{
if($a==3)
break
print"$a ";
}
Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在
break
之后缺少分号了解程序为何会这样运行是相当有趣的。
PHP 中
break
的一般语法是:表达式是可选的,但如果存在,其值会告诉您嵌套了多少个
封闭的结构将被打破。
break 0;
和break 1;
与break;
相同您的代码相当于
现在的 PHP 中的
print
函数始终返回1
。因此,它相当于当
$a
为3
时,您打印其值并中断。建议使用大括号将条件或循环的主体括起来,即使主体只有一条语句。在这种情况下,将
if
主体括在大括号中:会产生语法错误:PHP 需要一个
;
但找到一个}
以上所有也适用于 PHP
continue
。 程序也会打印3
。因此,出于类似的原因,
Missing semi-colon after
break
It's rather interesting to know why your program behaves the way it does.
The general syntax of
break
in PHP is:The expression is optional, but if present its value tells how many nested
enclosing structures are to be broken out of.
break 0;
andbreak 1;
are same asbreak;
Your code is equivalent to
Now the
print
function in PHP always return1
. Hence it is equivalent toso when
$a
is3
you print its value and break.It's advisable to use braces to enclose the body of a conditional or a loop even if the body has a single statement. In this case enclosing the
if
body in braces:would have given a syntax error: PHP expects a
;
but finds a}
All of the above applies to the PHP
continue
as well. So the programalso prints
3
for a similar reason.您在中断末尾缺少一个分号。 ;)
即使使用分号,它也不会像您期望的那样工作,因为它将从
0
计数到2
。你必须这样写才能得到1 2
。注意 $a 现在是 for 循环初始化中的一个。
编辑:我注意到的另一件事你应该注意。在 for 循环控制中,您有一个预增量 (
++$a
)。这基本上意味着 PHP 递增$a
的值,然后返回$a
。另一种选择是后递增 ($a++
),其中返回$a
,然后递增 1。在你的情况下,两种方法都会得到正确的输出。
这有时非常重要。请记住这一点。
You are missing a semicolon at the end of break. ;)
And even with the semicolon it will not work as you'd expect it to since it will count from
0
to2
. You have to write it like this to get only1 2
.Note $a is now one in the for loop initialization.
EDIT: Another thing I've noticed which you should be aware of. In your for loop control you have a pre-increment (
++$a
). That basically means that PHP increments the value of$a
and then returns$a
. Another option is the post-increment ($a++
) where$a
gets returned and then gets incremented by one.In your case both ways will get you the correct output tho.
This sometimes is pretty important. Just keep that in mind.
正如 codaddict 所说,你在休息后错过了分号。
您的代码应如下所示:
As codaddict said, you are missing the semi-colon after break.
Your code should look like:
@Downvoters:除了我简洁之外还有什么问题?
@Downvoters: What's wrong aside from me being laconic?
使用
echo
代替print
。Use
echo
in place ofprint
.