全部问题 > 当前问题

..................

if(!x) y  ; else { if(x==0) { if(x) y =2; else y =3; } }老师为什么到x==0为假就直接结束执行了啊?

黄庆祥 2017-4-15 21:49:04

共 1 个回答

qqq 2017-4-25 09:55:07

因为没有跟else if并列的else了,如果else if里的条件为假,说明整个if语句已经没有可执行的部分了。

问题来自: 嵌套的if语句
有以下程序
#include <stdio.h>
main()
{ int x=1,y=0;
  if(!x) y++;
  else if(x==0)
    if (x) y+=2;
    else y+=3;
  printf("%d\n",y);
}
程序运行后的输出结果是 ______ 。
A. 3
B. 2
C. 1
D. 0
答案:D
解析:这道题目if嵌套的很混乱,根据else的就近原则,我先把格式给大家复原调整一下。 if(!x) y++; else { if(x==0) { if(x) y+=2; else y+=3; } } 由于x=1,因此!x为假,进入else。x==0为假,结束执行,y没有赋值。因此选D。