开发者

C: Problem with while loop

im trying to fix this while loop but keep running into errors. Basically lets pretend I have 4 turtles, for every turtle that I sell I get a coin. Once I get to 0 I want to print how many coins I have. The error im getting is this,

error parentheses around assignment used as truth value make: *** [cents] Error 1

Here is the code:

while (turtles > 0) {
turtles = turtles - 1;
coin++;
if (turtles = 0)
printf("Now you have %d coins\n", co开发者_JS百科in);
}


Be glad that your compiler gave you that error.

You are assigning 0 to turtles in your if condition:

if (turtles = 0)

I suppose you are trying to test if it is equal to 0. Then it should be two equals == for equality instead.

if (turtles == 0)


if (turtles = 0)
   printf("Now you have %d coins\n", coin);

The assignment operator would always assign 0 to turtles. The result would be boolean value [i.e false (in this case)] and you would never get the string printed.

What you meant was if (turtles == 0) and not if (turtles = 0).


I guess it has problem with your if condition. The condition you have stated is wrong anyways. It should be :

if (turtles == 0)

Yours would simply assign 0 to turtles.


Your if statement should be:

if(turtles == 0)

At the moment, it contains an assignment, which is why you're getting the error.

You may want to consider putting your print line after the while loop has terminated, since coins doesn't appear to be scoped to the while loop. If turtles is always going to be positive at the start of your block of code, then you wouldn't need the if statement, since the termination clause of the while loop would mean that turtles was 0 when it exited.

If you do still need the if statement (because turtles may start off at -1 for example), then moving the if statement out of the while clause would probably still offer you a small performance improvement since the evaluation wouldn't need to be performed for each loop iteration. In your specific case, given the small number of iterations, the impact would be minimal (the compiler may even be optimizing it for you), but it's something you might want to consider for the future.

while (turtles > 0) {
    turtles = turtles - 1;
    coin++;
}
if (turtles == 0)  // not needed if turtles is unsigned
    printf("Now you have %d coins\n", coin);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜