簡體   English   中英

C:我的循環似乎無效

[英]C: My loop doesn't seem to work

我是C語言的新手,今天我遇到了一個無法解決的問題,因此我需要一些幫助。 我們得到了以下任務:

“編寫一個演示使用“預讀”技術的“ while”循環的程序:它要求用戶輸入(包括)10和100之間的數字,輸入零將終止循環。 如果輸入的數字小於10或大於100,則會顯示一條錯誤消息(例如,“錯誤:不允許250”)。 循環終止后,程序將打印輸入的數字。

我遇到的問題是,一旦輸入有效數字(介於10到100之間),程序就會靜止不動,它不會終止也不會循環。 另一方面,如果我輸入8、102之類的無效數字,則會循環執行printf(“ Error,不允許%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);

}

您必須在循環要求輸入數字:

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

並且請檢查scanf的返回碼以檢測錯誤。

最后,您在循環內將計數器增加兩次。

問題是您應該在循環內閱讀:

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次。

請注意,此代碼段還將使counter遞增0。如果不需要,則除0以外的數字為counter-1。

您的while循環陷入了無限循環。 您將條件設置為“ WHILE(num> 0)”,但實際上您從未更改過它。 這就是為什么當您的num越界時代碼會被捕獲的原因。

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

}

這是因為您必須從循環內的輸入(scanf)獲取數字。 否則,循環將永遠循環(如果輸入的最合適的數字> 0)。 如果無效,您會看到輸出。

已經共享的答案是正確的,您需要在循環中要求輸入。 另外,您需要為用戶提供退出循環的方法(例如,前哨),如果您知道輸入將為非負值,則可以將變量定義為“ unsigned int”,而不是只是“ int”。 參見下面的方法。

    #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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM