4 程序流程构造
C++反对最根本的三种程序运行构造:
- 程序构造
- 抉择构造
- 循环构造
4.1 抉择构造
4.1.1 if 语句
作用:执行满足条件的语句
if 语句能够嵌套叠加
单行格局 if 语句
if(条件){条件满足需要执行的语句;}
多行格局 if 语句
if(条件){条件满足执行的语句}else{条件不满足执行的语句}
多条件 if 语句
if(条件){满足的语句}else if(条件2){满足条件1但不满足条件2的语句}…else{都不满足的语句};
练习案例
有三只小猪ABC,请别离输出三只小猪的体重,并判断谁最重。
#include<iostream>#include<string>using namespace std;class Pig { string name; int weight;public: Pig() { cout << "Pig constructed." << endl; } ~Pig() { cout << "Pig disconstructed." << endl; } void setName(string n) { name = n; } void setWeight(int w) { weight = w; } int getWeight() { return weight; } string getName() { return name; }};int main() { string name; int weight; Pig pigA; cout << "Please enter the name of pig A: "; cin >> name; pigA.setName(name); cout << "Please enter the weight of pig A: "; cin >> weight; pigA.setWeight(weight); Pig pigB; cout << "Please enter the name of pig B: "; cin >> name; pigB.setName(name); cout << "Please enter the weight of pig B: "; cin >> weight; pigB.setWeight(weight); Pig pigC; cout << "Please enter the name of pig C: "; cin >> name; pigC.setName(name); cout << "Please enter the weight of pig C: "; cin >> weight; pigC.setWeight(weight); if (pigA.getWeight() >= pigB.getWeight() && pigA.getWeight() >= pigC.getWeight()){ cout << pigA.getName() << " is the heavieat." << endl; } else if (pigB.getWeight() >= pigA.getWeight() && pigB.getWeight() >= pigC.getWeight()){ cout << pigB.getName() << " is the heavieat." << endl; } else{ cout << pigC.getName() << " is the heavieat." << endl; } cin.get(); return 0;}
我在构造函数和解析函数中增加了输入语句。因而能够看出,如果不必new和delete的话,编译器也会主动地开释空间。
4.1.2 switch 语句
作用:执行多条件分支语句
语法:
switch(表达式){ case 后果1:表达式1;break; case 后果2:表达式2;break; case 后果3:表达式3;break; case 后果4:表达式4;break; case 后果5:表达式5;break; …… default:表达式6;}
留神:如果不加 break,前面的case之中的表达式会全副被执行!
if 和 switch 的区别;
switch 只能判断整型和字符型,不能判断一个区间
switch 构造清晰,执行效率更高。
问题:switch 能判断 C 格调或 C++ 格调字符串么?
答复:不行,然而能够判断枚举量。(早晨能够试一下)
尝试了一下枚举,感觉还不错。实际上枚举能够当成一组相干常量的应用办法,感觉用起来还是不错的。
#include<iostream>using namespace std;int main() { enum Color{red,green,yellow}; Color color = red; int i = color; i++; color = Color(i); switch (color) { case red: cout << "The color is red." << endl; break; case green: cout << "The color is green. " << endl; break; case yellow: cout << "The color is yellow. " << endl; break; } return 0;}
4.2 循环构造
4.2.1 while 循环
作用:满足循环条件,执行循环语句
语法:while( 循环条件 ){ 循环语句 }
4.2.2 do while 循环
作用:先执行,再一直循环执行语句
语法:
do{ 循环语句;}while( 循环条件 );
PS. 须要留神,这个语句在while(循环条件)
后须要加上分号。它相当于整个 do while 语句的完结。
#### 4.2.3 for 循环
作用:满足条件,执行循环语句
语法:for(起始表达式. 条件表达式, 开端循环体){循环语句}
4.3 跳转语句
break: 跳出以后循环或 switch
continue: 完结这一次循环进入下一个循环
goto: 跳转到你标记的地位,能够用来跳出多层循环
语法:
goto 标记;……标记:……
留神:标记的名称个别用纯大写;跳转的标记处,应该用冒号。