第五章 5.4.4节练习 & 5.5.1节练习 & 5.5.2节练习 & 5.5.3节练习
来源:互联网 发布:数据统计分析相关工作 编辑:程序博客网 时间:2024/06/06 16:01
练习5.18
说明下列循环的含义并改正其中的错误。
(a)
do
int v1, v2;
cout << "Please enter two numbers to sum:";
if (cin >> v1 >> v2)
cout << "Sum is: " << v1 + v2 << endl;
while(cin);
(b)
do{
//...
}while(int ival = get_response());
(c)
do{
int ival = get_response();
} while(ival);
解答:
(a) do while缺少大括号
(b) 如果ival在块中使用到了,那么这段代码就错了
(c) 编译器会提示未定义ival。
int ival;do{ ival = get_response();} while(ival);
练习5.19
编写一段程序,使用do while循环重复执行下述任务:首先提示用户输入两个string对象,然后填出较短那个并输出它。
解答:
#include <iostream>#include <string>using namespace std;int main(){do{string str1, str2;cout << "Please enter two string:\n";cin >> str1 >> str2;cout << (str1.size() < str2.size() ? str1 : str2) << endl;} while (cin);}
练习5.20
编写一段程序,从标准输入中读取string对象的序列直到连续出现两个相同的单词或者所有单词都读完位置。使用while循环一次读取一个单词,当一个单词连续出现两次时使用break语句终止循环。输出连续重复出现的单词,或者输出一个消息说明没有任何单词是连续重复出现的。
解答:
#include <iostream>#include <string>using namespace std;int main(){string word_new, word_old;bool flag = true;while (cin >> word_new){if (word_new == word_old){cout << word_old << " is duplicated." << endl;flag = false;break;}word_old = word_new;}if (flag){cout << "no words duplicate." << endl;}}
练习5.21
修改5.51节练习题的程序,使其找到的重复单词必须以大写字母开头。
解答:
#include <iostream>#include <string>#include <cctype>using namespace std;int main(){string word_new, word_old;bool flag = true;while (cin >> word_new){if (word_new == word_old && isupper(word_new.at(0))){cout << word_old << " is duplicated." << endl;flag = false;continue;}word_old = word_new;}if (flag){cout << "no words duplicate." << endl;}}这个是找到全部满足条件的单词。
练习5.22
本节的最后一个例子跳回到begin,其实是用循环能更好地完成该任务。重写这段代码,注意不再是用goto语句。
解答:
while(1){ int sz = get_size(); if(sz <= 0) continue;}
0 0
- 第五章 5.4.4节练习 & 5.5.1节练习 & 5.5.2节练习 & 5.5.3节练习
- 第五章 5.4.1节练习 & 5.4.2节练习
- 第五章 5.2节练习 & 5.3.1节练习
- 第五章 5.1节练习
- 第五章 5.6.3节练习
- 第五章 5.3.2节练习
- C++Primer第五版 5.5.3节练习
- C++Primer第五版 5.5.2节练习
- C++Primer第五版 5.5.1节练习
- 第十八章 18.1.3节练习 & 18.1.4节练习
- 第二章 2.4.4节练习 & 2.5.2节练习
- 第九章 9.2.2节练习 & 9.2.3节练习
- 第九章 9.3.2节练习 & 9.3.3节练习
- 第十四章 14.9.2节练习 & 14.9.3节练习
- 第十五章 15.7.2节练习 & 15.7.3节练习
- 第十七章 17.5.2节练习 & 17.5.3节练习
- 第二章 2.2.2节练习 & 2.2.3节练习
- 第四章 4.1.2节练习 & 4.1.3节练习
- 随意一写
- HTML5--web存储学习笔记
- 【干货】Scrapy安装配置
- Linux mint 17 安装fcitx
- 消除SDK更新时的“https://dl-ssl.google.com refused”错误
- 第五章 5.4.4节练习 & 5.5.1节练习 & 5.5.2节练习 & 5.5.3节练习
- Cocos2d-JS win7下bindings-generator使用非r9b的NDK版本
- Android 三维空间 代码 研究
- 五位数的水仙花数
- Swift基础--使用TableViewController自定义列表
- SEO新手入门要点
- Best Time to Buy and Sell Stock II
- C 与 C++ 头文件类型
- 【Visual C++】游戏开发笔记之七——基础动画显示(一)定时器的使用