C++ Primer 中文版(第 5 版)练习解答合集
自己写的解答,如有错误之处,烦请在评论区指正!
#include <iostream>
using namespace std;
int main() {
unsigned int maxCnt = 0, cnt = 0;
string now, last, maxString;
while (cin >> now) {
if (now == last) {
++cnt;
if (cnt > maxCnt)
maxCnt = cnt;
maxString = now;
} else {
last = now;
cnt = 0;
}
}
cout << "连续出现次数最多的单词是:" << maxString << '\n'
<< "出现了 " << maxCnt << " 次。" << endl;
return 0;
}
- a.
ix
从0
开始循环到sz - 1
为止,循环次数为sz
。错误:ix
仅在for
内可见。
b.for
缺少对ix
的初始化语句(实在不想写也要放个;
当空语句)
c. 如果循环体内 - 如果只能选一种,我选
while
,感觉写起来更自由。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> a{0, 1, 1, 2};
vector<int> b{0, 1, 1, 2, 3, 5, 8};
int len = a.size() < b.size() ? a.size() : b.size();
bool prefix = true;
for (int i = 0; i != len; ++i) {
if (a[i] != b[i]) {
prefix = false;
break;
}
}
if (prefix)
cout << (a.size() < b.size() ? "a" : "b") << "是前缀" << endl;
else
cout << "没有前缀" << endl;
return 0;
}
- a. 不断请求用户输入两个数字并输出他们的和,如果没有输入则退出循环。错误:
do
后面的语句需要花括号。
b. 不断循环,直到get_response()
的返回值为 0。错误:将变量声明放在了条件部分。
c. 不断循环,直到get_response()
的返回值为 0。错误:最好把ival
的定义写在外面。
#include <iostream>
#include <string>
using namespace std;
int main() {
string a, b;
cout << "Please input two strings: " << endl;
cin >> a >> b;
do {
cout << (a.size() < b.size() ? a : b) << endl;
cout << "Please input two strings: " << endl;
} while (cin >> a >> b);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
bool flag = false;
string last, now;
while (cin >> now) {
if (now == last) {
flag = true;
break;
}
last = now;
}
if (flag)
cout << "Repeat word: " << now << endl;
else
cout << "No repeat word." << endl;
return 0;
}
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
bool flag = false;
string last, now;
while (cin >> now) {
if (now == last) {
if (!isupper(now[0]))
continue;
flag = true;
break;
}
last = now;
}
if (flag)
cout << "Repeat word: " << now << endl;
else
cout << "No repeat word." << endl;
return 0;
}
do {
int sz = get_size();
} while (sz <= 0);
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << a / b << endl;
return 0;
}
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
if (b == 0)
throw runtime_error("b cannot be 0.");
else
cout << a / b << endl;
return 0;
}
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int a, b;
while (cin >> a >> b) {
try {
if (b == 0)
throw runtime_error("b cannot be 0.");
cout << a / b << endl;
} catch (runtime_error err) {
cout << err.what()
<< "\nTry again? Enter y or n" << endl;
char c;
cin >> c;
if (!cin || c == 'n')
break;
}
}
return 0;
}