简体   繁体   中英

Why does this loop in C not work?

I'm trying to make a loop so that a user can enter a number, and after each number they are prompted if they want to enter another number or not. If they choose anything but n or N , then count is increased, so the loop keeps going, but instead it doesn't!

#include <stdio.h>

main() {

    int nums[10], i, tot = 0;
    int answer;
    double avg;

    int count = 1;

    for (i = 0; i < count; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &nums[i]);
        printf("Enter another number? ");
        scanf(" %c", &answer);
        tot += nums[i];
        if (answer != 78 && answer != 110) {
            count++;
        }
        else { count = count - 1; }
        printf("[c:%d][i:%d]", count, i);
    }

}

The output I get:

Enter number 1: 2
Enter another number? y
[c:2][i:0]Enter number 2: 3
Enter another number? y
[c:3][i:1]Enter number 3: 4
Enter another number? n
[c:4][i:2]Enter number 4: 1
Enter another number? n
[c:5][i:3]Enter number 5: 2
Enter another number? n
[c:6][i:4]Enter number 6: 2
Enter another number? n
[c:7][i:5]Enter number 7: ^C

the count variable does not decrement when I enter n or N , why not? It's supposed to decrement to exit out of the loop, and using break; doesn't work either!

you probably want to make answer of type char instead of int.

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