簡體   English   中英

如何解決我面臨的 C 程序中的這個無限循環問題?

[英]How to solve this infinite loop problem in C program I am facing?

當我在第一次沒有輸入的情況下運行它兩次時,我得到了下面顯示的程序的無限循環。 但是,當我在第一次運行時提供輸入時,它運行得很好。

但是,如果我運行一次但不提供輸入並重新運行它,則會導致無限循環。

我該如何解決這個問題?

我正在使用 VS 代碼。

源代碼:

/*  UNIT CONVERSION
kms to miles
inches to foot
cms to inches
pound to kgs
inches to meters

*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
    int x;
    float a;
start:
    printf("\nSelect the type of unit conversion you want\nkms to miles\tPRESS 1\ninches to foot\tPRESS 2\ncms to inches\tPRESS 3\npound to kgs\tPRESS 4\ninches to meters\tPRESS 5\nPRESS 0 TO EXIT\n");
    scanf("%d", &x);
    switch (x)
    {
    case 0:
        goto end;

    case 1:
        printf("Enter the value in Km to be converted into miles\n");
        scanf("%f", &a);
        printf("%f kms is %f miles\n", a, 0.621371 * a);
        goto start;

    case 2:
        printf("Enter the value in inches to be converted to foot\n");
        scanf("%f", &a);
        printf("%f inches is %f feet\n", a, 0.0833333 * a);
        goto start;

    case 3:
        printf("Enter the value in cms to be converted to inches\n");
        scanf("%f", &a);
        printf("%f cms is %f inches\n", a, a * 0.393701);
        goto start;

    case 4:
        printf("Enter the value in pound to be converted to kgs\n");
        scanf("%f", &a);
        printf("%f pound(s) is equal to %f kgs", a, a * 0.453592);
        goto start;

    case 5:
        printf("Enter the value in inches to be converted to metres\n");
        scanf("%f", &a);
        printf("%f inch(es) is equal to %f metre(s)", a, a * 0.0254);
        goto start;

    default:
        printf("You have not entered a valid input :(\n");
        goto start;
    }
end:
    printf("You have successfully exited the program\n");
    return 0;
}

如果您不提供任何輸入,這可能意味着您只是按回車鍵,則scanf將失敗並且不會設置x變量。

if (scanf("%d", &x) != 1) {
    x = -1;
}

如果沒有給出數字,這會將x 設置為無效值。 該代碼檢查scanf是否確實進行了 1 次轉換。

始終檢查scanf進行了請求的轉換次數。

並停止使用goto 使用適當的whilefordo while循環。

暫無
暫無

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

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