您的位置:首页 > 编程语言 > C语言/C++

【c++应用程序设计】第2章 控制流

2014-08-07 06:02 211 查看
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;

2.3 while语句
执行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语句需要事先指定循环次数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: