【问题标题】:Why is the last condition not executing?为什么最后一个条件没有执行?
【发布时间】:2021-07-24 04:31:00
【问题描述】:

【问题讨论】:

  • 提示:if/else 的 else 部分仅在原始条件为假时执行。因此,如果100 <= a && a <= 200 为真,那么代码将printf("The integer %d lies between 100 and 200",a) 并跳过其他所有内容。
  • 非常感谢您的帮助

标签: c if-statement control-flow logical-and


【解决方案1】:

我建议您重新阅读 if-else 的基础知识。使用 if-else 时,条件是按顺序检查的,一旦其中一个匹配,则执行该块,其余的将被忽略。

在您的情况下,当 100

最简单的解决方法是从 if((100<=a&&a<=200)&&(100<=b&&b<=200)) 开始,然后输入其他 else if 条件。

【讨论】:

  • 非常感谢,我会再做一遍。非常感谢!!
  • 另外,你能不能参考一些学习C的材料,我是从这里和那里自己学习的。谢谢你的问候
【解决方案2】:

仅当其关联的 if 条件评估为 0 时,才会考虑 else 块。

在您的情况下,如果 a 和 b 都介于 100 和 200 之间,则将采用第一个 if (100<=a&&a<=200),然后跳过其 else 块。 如果您编写 if-else 块而不省略括号,它可能会帮助您了解为什么会出现这种情况:

if (100<=a && a<=200){
    printf("The integer %d lies between 100 and 200",a);
} else {
    if (100<=b && b<=200) {
        printf("The integer %d lies between 100 and 200",b);
    } else {
        if((100<=a && a<=200) && (100<=b && b<=200)) {
            printf("Both of the integers lie between 100 and 200");
        } else {
            printf("The integers does not lie between 100 and 200");
        }
    }
}

【讨论】:

    【解决方案3】:

    因为您需要了解更多关于 if and else statement in c 的内容,如果 a 在 [100...200] 之间,则检查 b 是否在 [100..200] 之间,如果不检查这两个条件你刚才忽略了?

    我建议你像这样使用布尔值,这样如果你看不到它就足够明显了

    #include<stdio.h>
    int main()
    {
    int a,b;
    printf("Enter the first integer:");
    scanf("%d",&a);
    printf("Enter the second integer:");
    scanf("%d",&b);
    int x,y;
    x=100<=a&&a<=200; // returns 1 if it's between 100 and 200
    y=100<=b&&b<=200; // returns 1 if it's between 100 and 200
    if ((x==1) && (y==1))
    printf("Both of the integers lie between 100 and 200");
    else {
      if(x==1)
         printf("The integer %d lies between 100 and 200",a);
      else if (y==1) 
         printf("The integer %d lies between 100 and 200",b);
      else 
        printf("The integers does not lie between 100 and 200");}
    }
    

    注意:if you have one statement in each condition or a loop it's usless to open brackets

    【讨论】:

    • 对于你关于学习 C 的问题,只需搜索带有解决方案的练习,但不要潜入解决方案,直到你努力解决它@sankalpshady
    【解决方案4】:

    例如 if 语句中的条件

    if (100<=a&&a<=200) 
    

    判断为逻辑真,则其他 if-else 语句将不被执行,包括这个 if 语句

    else if((100<=a&&a<=200)&&(100<=b&&b<=200))
    

    你需要从这个语句开始你的 if-else 语句

    if((100<=a&&a<=200)&&(100<=b&&b<=200))
    {printf("Both of the integers lie between 100 and 200");}
    else if (100<=a&&a<=200)
    {printf("The integer %d lies between 100 and 200",a);}
    else if (100<=b&&b<=200)
    {printf("The integer %d lies between 100 and 200",b);}
    else
    {printf("The integers does not lie between 100 and 200");}
    

    【讨论】:

    • 非常感谢!!
    • 能否请您参考一些学习C的材料,我是从这里和那里自己学习的。谢谢你的问候
    • @sankalpshady 很抱歉,我阅读的唯一文档是 C 标准草案。你可以在互联网上找到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2017-02-08
    • 2018-05-10
    • 2014-04-05
    • 1970-01-01
    相关资源
    最近更新 更多