if语句是一种基本的条件控制语句,它的语法基本跟自然语言中的英语一样(if something happens, do something)。if语句后面还可以选择的加上 else 语句(if something happen,do something ,else ,do other things)。
基本if语句
#include <iostream>
using namespace std;
//基本if语句
int main()
{
int num = 5 ;
if ( num > 4 )
cout <<"数字大于4." << endl;
num = 3 ;
if ( num > 4 )
cout << "数字大于4。" << endl;
else
cout << "数字小于等于4." << endl;
return 0 ;
}
结果:
#include<iostream>
using namespace std;
//多行if语句
int main()
{
int num = 5 ;
int cnt = 0 ;
if ( num > 4 )
{
cout << "数字大于4." << endl;
cnt++;
}
num = 3 ;
if (num > 4)
{
cout << "数字大于4。" << endl;
cnt++;
}
else
{
cout << "数字小于等于4." <<endl;
cnt++;
}
cout << "cnt=" <<cnt <<endl;
return 0;
}
运行结果:
为了增强程序的可读性,我们一般会在不同的场合为语句添加缩进(一般只要看到左花括号就缩进,看到右花括号就减少缩进)。缩进在c++中只会被当做空格处理,并不会对语义造成任何影响。
else if 的应用:
#include <iostream>
using namespace std;
//else if 的应用
int main()
{
int num = 5;
if (num < 4)
{
cout << "数字小于4." <<endl;
}
else if ( num > 6)
{
cout << "数字大于6." << endl;
}
else
{
cout << "数字在4和6之间。" <<endl;\
}
return 0;
}
运行结果:
#include<iostream>
using namespace std;
//嵌套if语句
int main()
{
bool isNorth = true;
bool isWest = false;
if ( isNorth )
{
if (isWest)
{
cout <<"西北方向!" << endl;
}
else
{
cout << "东北方向!" << endl;
}
}
else
{
if (isWest)
{
cout << "西南方向!" << endl;
}
else
{
cout << "东南方向!" << endl;
}
}
return 0 ;
}
运算结果:
悬垂 else:
#include<iostream>
using namespace std;
//悬垂else
int main()
{
int a = 4;
if ( a > 3 )
if ( a > 5 )
cout <<"a大于5!" << endl;
else
cout << "a小于等于3!" <<endl;
return 0;
}
运行结果:
如果本文对你有帮助请点赞支持一下下~
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- huatuo8.com 版权所有 湘ICP备2023022238号-1
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务