“我的问题是,为什么第一个“for”语句在递增“1”后立即进行,而在第二个“for”语句中,循环继续进行,直到 d 的值不再小于 p,然后再继续最终的“if”语句和 NSLog。”
您似乎对 for 循环的工作原理有点困惑。
// Outer loop will run 1 time
for (int i = 0; i < 1; i++) {
NSLog(@"Outer loop = %d", i);
// Innter loop will run 10 times
for (int j = 0; j < 10; j++) {
NSLog(@"Inner loop = %d", j);
}
}
上面的循环打印出以下输出:
Outer loop = 0
Inner loop = 0
Inner loop = 1
Inner loop = 2
Inner loop = 3
Inner loop = 4
Inner loop = 5
Inner loop = 6
Inner loop = 7
Inner loop = 8
Inner loop = 9
编辑:
- (int)isPrime
{
@autoreleasepool {
// Outer loop will run once to check if 15 is prime
for (int p = 15; p <= 15; ++p) {
// You set isPrime to 1
int isPrime = 1;
// Inner loop will start at 2 and run until 14, there is no
// need to check if 15 % 1 or 15 % 15 because a prime number is
// divisible by itself or 1
for (int d = 2; d < p; ++d) {
NSLog(@"%d mod %d", p, d);
// The first run through of the inner loop, you check if
// 15 % 2, this is not true, so you skip to the next loop.
if (p % d == 0) {
isPrime = 0;
//break; // This is optional because at this point, you know p is not prime
}
// Remember you set isPrime to 1, so the loop checks if isPrime != 0
// This statement is true, so you print p which at this point is 15.
if (isPrime != 0) {
NSLog (@"%i ", p);
}
// On the next run through of the inner loop, 15 % 3 is equal to
// 0, so you set isPrime to 0, and for the rest of the inner loop
// isPrime is equal to 0, it can not change, this is why p is never
// printed out again
}
}
}
return 0;
}
我在内循环中添加了一条日志语句。继续运行我的代码,这样你就可以看到发生了什么。我会这么说,你的代码看起来不错。如果 isPrime 等于 0,您知道 p 是否为素数,因此添加一个 break 语句将是一个好主意。检查代码以查看放置它的位置。