if语句及其嵌套

if语句:根据条件决定控制流
if语句:
if(condition)
   statement

if else语句:
if(condition)
   {statement1}
else
   {statement2}

condition可以是一个表达式,也可以是一个初始化了的变量声明,其类型都可以转换成布尔类型,condition为真,则执行ststement
如:

a=5,b=2;
if(a)  //等价于a!=0
x=a*10;


悬垂else:规定else与离它最近的尚未匹配的if匹配,要想使else分支和外层的if语句匹配,可以在内层if语句的两端加上{ },使其成为一个块

//计算三角形面积
	double a, b, c;
	cin >> a >> b >> c;
	if (a + b > c && a + c > b && b + c > a) {
		double s, t;
		t = (a + b + c) / 2.0;
		s = sqrt(t * (t - a) * (t - b) * (t - c));
		cout << "area=" << s << endl;
	}
	else
		cout << "error" << endl;
//判断是否为闰年
	int year;
	bool isLeapYear;
	cout << "Enter the year:";
	cin >> year;
	isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
	if (isLeapYear)
		cout << year << "is a leap year" << endl;
	else
		cout << year << "is not a leap year" << endl;
	system("pause");
	return 0;

 if的嵌套1:
if(表达式1) 语句1
else if(表达式2) 语句2
else if(表达式3) 语句3
else if(表达式n) 语句n
else 语句m

//输出成绩分类
int score;
cin >> score;
if (score >= 90)  cout << "A" << endl;
else if (score >= 80) cout << "B" << endl;
else if (score >= 70) cout << "C" << endl;
else if (score >= 60) cout << "D" << endl;
else cout << "E" << endl;

if的嵌套2:
if(表达式1)
   if(表达式2) 语句1
   else 语句2
else
   if(表达式3)语句3
   else 语句4 

/*计算分段函数  
x-1,x<-3
y=9-x,-3<=x<=3
x+1,x>3*/

double x,y;
cin>>x;
if(x<-3.0)  y=x-1.0
else
   if(x>=-3.0&&x<=3.0)
     y=9-x;
   else y=x+1;


版权声明:本文为m0_68095107原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。