C:我的循环似乎不起作用

时间:2013-11-19 21:28:17

标签: c loops while-loop

我是C的新手,今天我遇到了一个我无法弄清楚的问题,所以我需要一些帮助。我们已经完成了这项任务:

'编写一个演示使用'预读'技术的'while'循环的程序:它要求用户在10和100之间输入数字(包括),输入零会终止循环。如果输入的数字小于10或大于100,则显示错误消息(例如“错误:250不允许”)。循环结束后,程序会打印输入的数字量。'

我遇到的问题是,一旦输入有效数字(10-100之间),程序就会静止不动,它不会终止也不会循环。另一方面,如果我输入一个非有效数字,如8,102,它会循环printf(“错误,%d不允许\ n”,num);

这是代码:

#include <stdio.h>


main(void)

{

int num;
int counter=1;

printf("Please type in your number between (and including) 10-100\n");
scanf("%d", &num);

if((num <10) || (num >100))
{
    printf("Error, %d is not allowed\n", num);
}

while (num > 0)
{
    counter++;

    if((num <10) || (num >100))
    {
        printf("Error, %d is not allowed\n", num);
    }
    counter++;
}


printf("%d numbers were entered!\n", counter);

}

6 个答案:

答案 0 :(得分:2)

你必须要求里面的循环:

printf("Please type in your number between (and including) 10-100\n");
scanf("%d", &num);

请检查scanf的返回代码以检测错误。

最后,你在循环内增加你的计数器两次。

答案 1 :(得分:1)

问题是你应该在循环中阅读:

while (num != 0)
{
    printf("Please type in your number between (and including) 10-100\n");
    scanf("%d", &num);

    if((num <10) || (num >100))
    {
        printf("Error, %d is not allowed\n", num);
    }
    counter++;
}

您也无需增加计数器2次。

请注意,此代码段也会增加0的计数器。如果不需要,则除0之外的数字是计数器 - 。

答案 2 :(得分:1)

你的while循环陷入无限循环。您设置条件“WHILE(num&gt; 0)”,但实际上您从未实际更改它。这就是当你的num在边界时代码被捕获的原因。

答案 3 :(得分:1)

#include <stdio.h>

void main(void)
{
    int num = 0, counter = 0;

    printf("Please type in your number between (and including) 10-100\n");

    do
    {
        printf("? ");
        scanf("%d", &num);
        if (!num)
            break;
        else if((num < 10) || (num > 100))
            printf("Error, %d is not allowed\n", num);
        counter++;
    } while (num);

    printf("%d numbers were entered!\n", counter);

}

答案 4 :(得分:0)

这是因为你必须从循环中的输入(scanf)中获取数字。否则循环将永远循环(如果输入的最合适的数字是> 0)。如果它无效,你会看到输出。

答案 5 :(得分:0)

已经分享的答案是正确的,您需要在循环中询问输入。此外,您需要为用户提供一种退出循环的方法(例如,一个标记),如果您知道输入将是非负的,那么您可以将变量定义为&#34; unsigned int& #34;而不只是&#34; int&#34;。请参阅下面的方法。

    #include <stdio.h>

    int main(void)
    {
       unsigned int num = 0, counter = 0;

       while (num != -1) // need to control with a sentinel to be able to     exit
    {
        printf("Please type in your number between (and including) 10-100. Enter \"-1\" to exit.\n");
        scanf("%d", &num);
        counter++; // increase the count by one each successful loop

        // set the non-allowed numbers
        if((num <10) || (num >100))
        {
            printf("Error, %d is not allowed\n", num);
            counter--; // Need to subtract 1 from the counter if enter a non-allowed number, else it will count them
        }

    } // end while loop

       printf("%d numbers were entered!\n", counter); // Show the use how many correct numbers they entered


    } // end main