为什么C中的循环不起作用?

时间:2012-04-04 21:46:17

标签: c

我正在尝试创建一个循环,以便用户可以输入一个数字,并在每个数字后提示他们是否要输入另一个数字。如果他们选择除nN之外的任何内容,则会增加计数,因此循环会继续,但不是!

#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);
    }

}

我得到的输出:

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

当我输入nN时,count变量不会减少,为什么不呢?它应该减少退出循环,使用break;也不起作用!

1 个答案:

答案 0 :(得分:7)

你可能想要answer类型char而不是int。