当前位置: 动力学知识库 > 问答 > 编程问答 >

Can't subtract in a for loop in C/Objective-C

问题描述:

I'm going through the Big Nerd Ranch book on Objective-C, which takes you through some early C stuff. I've played with C before, and am pretty experienced in PHP.

Anyhow, I'm doing the challenges and this one is not working the way I think it should. It's pretty simple - start at 99, loop through and subtract three until you get to zero, and every time you get a number that is divisible by 5 print "Found one." Pretty straightforward. However, subtracting by three in the for loop is not working

#include <stdio.h>

int main (int argc, const char * argv[])

{

int i;

for(i = 99; i > 0; i-3){

printf("%d\n", i);

if(i % 5 == 0) {

printf("Found one!\n");

}

}

return 0;

}

It creates and endless loop at 99, and I'm not sure why.

网友答案:

i-3 doesn't modify the variable i. Do something like -

 for( i=99; i>0; )
 {
      // ....
     i -= 3;
 }
网友答案:

It should be i-=3 instead of i-3.

#include <stdio.h>

int main (int argc, const char * argv[])
{

    int i;
    for(i = 99; i > 0; i-=3){
        printf("%d\n", i);
        if(i % 5 == 0) {
            printf("Found one!\n");
        }
    }
    return 0;
}

i-3 does not change the value of i.

i-=3 does.

网友答案:

Your loop statement doesn't modify the value of i. Just doing i - 3 doesn't change i, it just returns the value of i - 3.

Use: for(i = 99; i > 0; i = i - 3)

网友答案:

In the for loop, it should be i=i-3.

网友答案:

You are just subtracting 3 from i, but you are not assigning it to i. Use i = i - 3 instead of just i - 3.

Change your for statement like this:

for(i = 99; i > 0; i = i - 3) {
  // Write your code here.
}
网友答案:

The Last Term in the For loop is the increment of decrement operation. While i-3 is none. If you want the Value of i to get reduced by 3, then you should store that value in i itself.

To do that Following code should be written: i = i-3 or shorthand i-=3.

分享给朋友:
您可能感兴趣的文章:
随机阅读: