为什么最后一个条件没有执行?

问题描述

100

#include<stdio.h>
int main()
{
    int a,b;
    printf("Enter the first integer:");
    scanf("%d",&a);
    printf("Enter the second integer:");
    scanf("%d",&b);
    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");}
    return 0;
}

输出: enter image description here

解决方法

例如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");}
,

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

在您的情况下,当 100

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

,

一个 else 块仅在其关联的 if 条件评估为 0 时才被考虑。

在您的情况下,如果 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");
        }
    }
}
,

因为你需要了解更多关于 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