如何解决我在C程序中面临的这个无限循环问题?



当我第一次不给出输入而运行两次时,我得到了下面这个程序的无限循环。但是当我在第一次运行时输入时,它工作得很好。

但是如果我只运行一次,没有输入,然后重新运行,就会导致无限循环。

如何解决这个问题?

我用的是VS Code

源代码:

/*  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 wantnkms to milestPRESS 1ninches to foottPRESS 2ncms to inchestPRESS 3npound to kgstPRESS 4ninches to meterstPRESS 5nPRESS 0 TO EXITn");
    scanf("%d", &x);
    switch (x)
    {
    case 0:
        goto end;
    case 1:
        printf("Enter the value in Km to be converted into milesn");
        scanf("%f", &a);
        printf("%f kms is %f milesn", a, 0.621371 * a);
        goto start;
    case 2:
        printf("Enter the value in inches to be converted to footn");
        scanf("%f", &a);
        printf("%f inches is %f feetn", a, 0.0833333 * a);
        goto start;
    case 3:
        printf("Enter the value in cms to be converted to inchesn");
        scanf("%f", &a);
        printf("%f cms is %f inchesn", a, a * 0.393701);
        goto start;
    case 4:
        printf("Enter the value in pound to be converted to kgsn");
        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 metresn");
        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 programn");
    return 0;
}

如果您没有输入任何内容,您可能意味着您只是按enter键,scanf失败并且x变量将不会设置。

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

将x设置为无效值,如果没有给出数字。代码检查scanf实际上只进行了1次转换。

始终检查scanf请求的转换次数。

停止使用goto。使用适当的whilefordo while循环。