不懂 求详解
有以下程序
#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);
}
程序运行后的输出结果是 ______ 。
if(!x) y++;
else
{
if(x==0)
{ if(x)
y+=2;
else
y+=3;
}
}
x=1,因此!x为假,进入else。x==0为假,结束执行,y没有赋值
x=1; if(!x)为假,if(x==0)也为假,所以直接跳出不进行赋值,所以y=0;本题关键在于配对if else;配对原则是else对于最近的为配对的if所以整理出来的语句可以写成
if(!x)
{
y++;
}
else
{
if(x==0)
{
if(x) {y+=2;}
else y+=3;
}
}
将程序改写成下面的形式,注意分号才代表一条语句结束。所以后面
if(!x)
y++;
else
{
if(x==0)
{ if(x)
y+=2;
else
y+=3;
}
}
输入时x=1,y=0,下面的(!x)相当于(x==0),所以if(!x)为假,跳转到该if下面的else,然后判断if(x==0),显然为假,下面用小括号括起来的语句都是这个if对应的语句,它为假,所以不执行。继续跳转到下面的else,而这个else中没有内容,被省略了没写,故整个程序结束y没有被改变,依然为0.
有以下程序
#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。