大家中午好,今天我们来聊聊C++中if语句的使用。当C++程序必须决定是否执行某个操作时,通常使用if语句来实现选择。
if语句有两种格式:if和if else。if语句的语法与前面说过的while有点类似:
if(条件布尔表达式)
{
满足条件执行相应的操作
}
当条件布尔表达式为真,则执行满足条件的相应操作。而if else语法格式如下:
if(条件布尔表达式)
{
//满足条件
语句块1;
}
else
{
语句块2;
}
程序源代码如下:
#include <iostream>
using namespace std;
int main()
{
int lilei_score = 95;
int tom_score = 85;
if (lilei_score > 90)
{
cout <<"li lei score > 90" << endl;
}
cout << "li lei score is " << lilei_score << endl;
if (tom_score > 90)
{
cout <<"tom score > 90" << endl;
}
else
{
cout <<"tom score <= 90" << endl;
}
cout << "tom score is " << tom_score << endl;
return 0;
}
程序运行结果如下截图:
if 和if else语句就说到这,谢谢你的关注,下节课我们开始讲if else if的用法。