5.1 空语句:只含有一个单独的分号的语句。如:不需要循环的执行语句时
5.2 花括号括起来的部分。一条语句执行不完时使用块。
5.3 while(val<=10)sum+=val,++val;
5.4
(a) 每次循环创建一个迭代器,判断是否指向s尾部。不合逻辑,会一直执行下去。
(b) if语句无法访问status
5.5、5.6 略
5.7
(a) if(ival1!=ival2) ival1=ival2;
else ival1=ival2=0;
(b) if(ival
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
char stupid;
int vowel_cnt=0,space_cnt=0,ff_cnt=0,fl_cnt=0,fi_cnt=0;
while (cin.get(stupid))
{
switch (stupid)
{
case 'a':case 'o':case 'e':case 'i':case 'u':
case 'A':case 'O':case 'E':case 'I':case 'U':
++vowel_cnt; break;
case '\t':case ' ':case '\r':
++space_cnt; break;
case 'f':
cin.get(stupid);
switch (stupid)
{
case 'f': ++ff_cnt; break;
case 'l': ++fl_cnt; break;
case 'i': ++fi_cnt; ++vowel_cnt; break;
default:
break;
}
default:
break;
}
}
cout << "元音字母有" << vowel_cnt << "个" << endl;
cout << "空格有" << space_cnt << "个" << endl;
cout << "fl有" << fl_cnt << "个" << endl;
cout << "fi有" << fi_cnt << "个" << endl;
cout << "ff有" << ff_cnt << "个" << endl;
return 0;
}
5.13 略
5.14
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(int argc, char* argv[])
{
string stupid, temp=" ", max;
int max_cnt=0,temp_cnt=0;
while (cin >> stupid)
{
if (temp == stupid)
{
++temp_cnt;
if (temp_cnt > max_cnt)
{
max_cnt = temp_cnt;
max = temp;
}
}
temp = stupid;
}
if (max_cnt)cout << max << " appeared " << max_cnt << endl;
return 0;
}
5.15
(a) if语句不能访问ix
(b) 少了一个;
(c) 死循环
5.16 while循环。因为结构简单
5.17
#include<iostream>
#include<string>
#include<vector>
using namespace std;
bool qianzhui(vector<int> a, vector<int> b);
int main(int argc, char* argv[])
{
vector<int> first, second;
int temp = 0;
while (cin >> temp)
first.push_back(temp);
cout << "first:" << endl;
for (auto c : first)
cout << c << ' ';
cout << endl;
cin.clear();
while (cin >> temp)
second.push_back(temp);
cout << "second:" << endl;
for (auto c : second)
cout << c << ' ';
cout << endl;
if (qianzhui(first, second))cout << "true";
else cout << "false";
cout << endl;
return 0;
}
bool qianzhui(vector<int> a, vector<int> b)
{
if (a.size() > b.size())return false;
auto ptra = a.begin();
auto ptrb = b.begin();
for (; ptra != a.end(); ++ptra, ++ptrb)
{
if (*ptra != *ptrb)return false;
}
return true;
}
5.18 略
5.19
#include<iostream>
#include<string>
#include<vector>
using namespace std;
bool qianzhui(vector<int> a, vector<int> b);
int main(int argc, char* argv[])
{
string first, second;
do
{
if (first.size() > second.size())cout << second;
else cout << first;
cout << endl;
cout << "输入两个字符串" << endl;
} while (cin >> first >> second);
return 0;
}
5.22
int sz = get_size();
while (sz <= 0)
{
sz = get_size();
}
5.23-5.25
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(int argc, char* argv[])
{
try{
int a = 0, b = 0;
cout << "输入a" << endl;
cin >> a;
cout << "输入b" << endl;
cin >> b;
if (b == 0)
throw out_of_range("被除数为0");
cout << "结果是" << endl;
cout << a / b << endl;
}catch (out_of_range){
cout << "被除数为0" << endl;
//return -1;
}
return 0;
}