C++初学者,一定很简单,但想不明白,帮帮忙

来源:百度知道 编辑:UC知道 时间:2024/07/03 15:39:47
int x=2;
cout<<"Start\n";
if (x>3)
if(x!=0)
cout<<"Hello fron the second if.\n";
else
cout<<"Hello from else\n";
cout<<"End\n";
return 0;
这个语句输出结果为什么是 Start
End

你的程序的意思其实是下面的意思:
#include<iostream>
using namespace std;
int main()
{
int x=2;
cout<<"Start\n";
if (x>3)
{
if(x!=0)
cout<<"Hello fron the second if.\n";
else
cout<<"Hello from else\n";
}
cout<<"End\n";
return 0;
}
由于x<3,所以第二个if实际上没有判断就执行cout<<"End\n"; 了。

你的代码等同于下边:
int x=2;
cout<<"Start\n";
if (x>3)
{
if(x!=0)
{
cout<<"Hello fron the second if.\n";
}
else
{
cout<<"Hello from else\n";
}
}
cout<<"End\n";
return 0;

二楼说的对!