【问题标题】:I am not able to execute a program which includes user input of a integer inside an else if statement我无法执行在 else if 语句中包含用户输入整数的程序
【发布时间】:2019-11-05 08:23:27
【问题描述】:

当用户输入 1,2 或 3 时,程序退出而不扫描 else if 语句块中的数量。

如何在 if 或 else if 语句中进行扫描?

if (num==4)
{
    printf("exiting");
    goto end;
}

else
{
    if (num=='1')
    {
        printf("enter the value of the first unit\n");
        scanf("%f",&first);
        second=first*kmstomiles;
        printf("the value of the second unit is %f",second);
    }  

     else if (num=='2')
    {
         printf("enter the value of the first unit\n");
        scanf("%f",&first);
        second=first*inchestofeet;
        printf("the value of the second unit is %f",second);

    }
    else if (num=='3')
    {
        printf("enter the value of the first unit\n");
        scanf("%f",&first);
        second=first*cmtoinches;
        printf("the value of the second unit is %f",second);
    }

【问题讨论】:

  • 1'1' 是不同的。 1 是整数一,而 '1' 是字符一,即 49'1' 的 ASCII 值)。更改条件num=='1' --> num == 1

标签: c if-statement scanf


【解决方案1】:

请使用以下代码,

if (num==4)
{
    printf("exiting");
    goto end;
}

else
{
    if (num==1)
    {
        printf("enter the value of the first unit\n");
        scanf("%f",&first);
        second=first*kmstomiles;
        printf("the value of the second unit is %f",second);
    }  

     else if (num==2)
    {
         printf("enter the value of the first unit\n");
        scanf("%f",&first);
        second=first*inchestofeet;
        printf("the value of the second unit is %f",second);

    }
    else if (num==3)
    {
        printf("enter the value of the first unit\n");
        scanf("%f",&first);
        second=first*cmtoinches;
        printf("the value of the second unit is %f",second);
    }

【讨论】:

    猜你喜欢
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多