'for'语句中的'If'语句
问题描述:
在下面的Objective-C代码中,当第一个内部'if'语句满足(true)时,这是否意味着循环终止并转到下一个语句?'for'语句中的'If'语句
此外,当它执行一次后返回到内部'for'语句时,p的值是否再次为2,为什么?
// Program to generate a table of prime numbers
#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int p, d, isPrime;
for (p = 2; p <= 50; ++p) {
isPrime = 1;
for (d = 2; d < p; ++d)
if (p % d == 0)
isPrime = 0;
if (isPrime != 0)
NSLog (@”%i ", p);
}
[pool drain];
return 0;
}
在此先感谢。
答
您的代码equivilant这样:
// Program to generate a table of prime numbers
import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int p, d, isPrime;
for (p = 2; p <= 50; ++p) {
isPrime = 1;
for (d = 2; d < p; ++d) {
if (p % d == 0) {
isPrime = 0;
}
}
if (isPrime != 0) {
NSLog (@”%i ", p);
}
}
[pool drain];
return 0;
}
和该的if
内容for
控制语句是在括号中的下一条语句或语句块。
正如daveoncode所说,你真的应该使用大括号。
+0
谢谢。正如我上面所说的,我只是保留了我正在学习的一本书的原始代码,这就是为什么我感到困惑。现在,我认为这是有道理的。 但是,我不明白为什么当你再次回到这个内部陈述时,d的值又是2? – makaed
答
一个循环不会终止,直到发生以下情况之一:
- 一个回报遇到
- 的例外引发
- 遇到休息声明
- 循环的条件评估为假
ps。使用花括号,否则你的代码将无法读取/调试/ mantain
答
不,'if'语句解析为真将不会打破你的循环。循环继续执行,这可能是为什么你认为p仍然是2.它仍然是2,因为你仍然在内部循环。
最好的做法是总是在你的'for'和'if'语句中使用大括号,这会让你的代码更加清晰,并消除模糊性。 – Alex
我保留了其中一本教科书的原始代码。 – makaed