简体   繁体   中英

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", coin);
}

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)

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);
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 [ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM