【c++应用程序设计】第2章 控制流
来源:互联网 发布:项目数据分析师 上海 编辑:程序博客网 时间:2024/05/19 20:18
2.1 if-else语句
执行if-else语句时,先计算表达式的值。如果表达式为TRUE,先执行代码段1,再执行代码段2后面的语句。如果表达式的值为FALSE,则不执行代码段1,执行2和后续语句。
if-else语句可以没有else部分。
if-else语句中的代码段也可以是一个if-else语句。
<span style="font-family: Arial, Helvetica, sans-serif;">if (no_fish==1)</span> if (code<2) count<<"The water was too warm''<<endl; else count<<"The waters were all fished out''<<endl;
这段代码中外层if表示no_fish等于1的情况下,如果code小于2,则。。。其他情况,则。。。
对比下面代码:
int no_fish=1, code=2;if (no_fish==1){ if (code<2) count<<"The water was too warm"<<endl;}else count<<"The waters were all fished out"<<endl;count<<"***End of fish story***"<<endl;
如果使用多重嵌套,则代码逐步编译,找到TRUE值后后续语句不执行:
int code=2;if (code<=1) count<<"the water was wrong"<<endl;else if (code<=2) count<<"the water was too warm"<<endl;else if (code<=3) count<<"the waters were all fished out"<<<endl;else count<<"It was too later in the season"<<endl;count<<"***end of fishing excuses***<<endl;
执行while语句时,首先判断表达式是否成立,如果不成立,执行到成立为止。
int x=1;while (x!=2) x=x+1;count <<"x="<<x<<endl;
2.5 文件
如果要从磁盘文件中读取数据,用fstream头文件。
#include <fstream>using namespace std;const int cutoff=6000;const float rate1=0.2;const float rate2=0.3;int main(){ ifstream infile; ofstream outfile; infile.open ("income.in"); outfile.open (“tax.out"); int income, tax; infile>>income; while (income>=0){ if (income<cutoff) tax=rate1*income; else tax=rate2*income; outfile<<"income="<<income<<endl <<"tax="<<tax<<endl; infile>>income; }infile.close();outfile.close();return 0;}测试文件是否打开用if语句:
ifstream infile;infile.open ("scores.dat");if (!infile){ cout<<"unable to open scores.dat"<<endl; exit(0);}使用exit时要包含cstdlib头文件。
2.6 do-while语句
while语句在循环开始的位置检查,do-while在循环结束的位置检查。do-while是先执行代码,再检测表达式的值是t还是f。
2.7 for语句
for语句用于重复执行某段代码。for语句主要用于循环计数,for语句需要事先指定循环次数。
0 0
- 【c++应用程序设计】第2章 控制流
- 程序设计与C语言学习笔记_第三章第4章 语句及控制结构
- 第8章 51DOS应用程序设计
- 【c++应用程序设计】第0章 计算机系统及程序设计
- 《面向对象程序设计(C++)》第4章习题2
- 《Objective-C 2.0程序设计》第2章练习
- 第2章 控制流
- C程序设计(第10章)
- C程序设计(第3章)
- 第1章 程序设计和C语言
- C程序设计第6 7章
- .NET组件程序设计 第5章 版本控制
- Java程序设计(Java9版):第3章 流程控制
- 第25周-window程序设计(基础篇)-第2章-实例ScreenSize.c
- 第2章 基本程序设计
- 网易云课堂程序设计入门—C语言第四周 循环控制学习笔记
- 第6章 C控制语句:循环
- 【JavaSE入门系列】第10章_控制台应用程序设计
- 15.8 Pascal's Triangle
- USACO Letter Game 解题报告
- 部署中遇到的问题(四)
- Lucene 4利用Codec实现压缩存储
- Same Tree
- 【c++应用程序设计】第2章 控制流
- window批处理-5 start
- Python 访问Facebook (http)
- J2SE基础:10集合2
- 将C语言的字符串转为OC的字符串
- miRNA研究在线数据库
- 今日作息及食谱(8.7)
- geeksforgeeks Count number of binary strings without consecutive 1′s
- Ubuntu文件的复制、移动和删除命令