简体   繁体   English

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

[英]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!如果他们选择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);
    }

}

The output I get:我得到的 output:

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?当我输入nN时,计数变量不会递减,为什么不呢? It's supposed to decrement to exit out of the loop, and using break;它应该递减以退出循环,并使用break; doesn't work either!也不管用!

you probably want to make answer of type char instead of int.您可能希望answer类型为char而不是 int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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