本节书摘来自异步社区出版社《C++游戏编程入门(第4版)》一书中的第2章,第2.3节,作者:【美】Michael Dawson(道森),更多章节内容可以访问云栖社区“异步社区”公众号查看。
2.3 使用else子句
C++游戏编程入门(第4版)
在if语句中加入else子句可以引入只有当被验证的表达式为false时才执行的代码。下面给出包含else子句的if语句的形式:
if (expression)
statement1;
else
statement2;```
如果expression为true,执行statement1,然后程序跳过statement2,并执行if组合后面的语句。如果为false,跳过statement1,并执行statement2。当执行statement2后,程序执行if组合后面的语句。
###2.3.1 Score Rater 2.0程序简介
Score Rater 2.0程序同样用来评估用户输入的分数。但这次程序使用带else子句的if语句。图2.2和图2.3展示了基于用户输入的分数,程序显示的不同消息。
<div style="text-align: center">
<img src="https://yqfile.alicdn.com/abba19fa0a8e53aae5b90734c502cb1af952c041.png" >
</div>
从Cengage Learning网站(www.cengageptr.com/downloads)上可以下载到该程序的代码。程序位于Chapter 2文件夹中,文件名为score_rater2.cpp。
// Score Rater 2.0
// Demonstrates an else clause
include
using namespace std;
int main()
{
int score;
cout << "Enter your score: ";
cin >> score;
if (score >= 1000)
{
cout << "You scored 1000 or more. Impressive!n";
}
else
{
cout << "You scored less than 1000.n";
}
return 0;
}`
2.3.2 两种创建分支的方法
我们已经看到if语句的第一部分,它的工作方式和以往一样。如果score大于1000,则显示消息You scored 1000 or more. Impressive!。
if (score >= 1000)
{
cout << "You scored 1000 or more. Impressive!\n";
}```
下面是一个转折。如果表达式为false,则else子句提供了让程序分支运行的语句。因此,if (score >= 1000)的结果为false,程序跳过第一条消息而显示You scored less than 1000.。
else
{
cout << "You scored less than 1000.n";
}`