【C++ Primer(5th Edition) Exercise】练习程序 - Chapter5(第五章)

以下程序由 Teddy van Jerry (我自己)编写并运行,基本保证正确性。(有时可能会为优化程序超前使用某些内容)

Before we comb through the codes

这一章内容仍然非常好理解,我学习花了一天半(也不是一直在学C++)。主要原因是内容在之前大多已经出现过,因而再次介绍时就尤其轻松了。
Review:
【C++ Primer(5th Edition) Exercise】练习程序 - Chapter1(第一章)
【C++ Primer(5th Edition) Exercise】练习程序 - Chapter2(第二章)
【C++ Primer(5th Edition) Exercise】练习程序 - Chapter3(第三章)
【C++ Primer(5th Edition) Exercise】练习程序 - Chapter4(第四章)


TIP:标有(C++/11)者为C++/11标准下可以使用的题,若为老版本应加以修改。


Exercise 5.3

#include <iostream>
using namespace std;

int main()
{
    
    
	int sum = 0, val = 1;
	while (val <= 10)
		sum += val, ++val; // equivalent to sum += val, val++;
	cout << sum << endl;
	return 0;
}

其实,也可以简写成这样:

#include <iostream>
using namespace std;

int main()
{
    
    
	int sum = 0, val = 1;
	while (val <= 10)
		sum += (val++);
	cout << sum << endl;
	return 0;
}

Exercise 5.5

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    
    
	unsigned short score;
	while (cin >> score && score <= 100)
	{
    
    
		string grade;
		vector<string> vec{
    
     "F","D","C","B","A","A++" };
		if (score < 60) grade = vec[0];
		else
		{
    
    
			grade = vec[(score - 50) / 10];
			if (score % 10 < 3 && score != 100)
				grade += "-";
			else
			{
    
    
				if (score % 10 > 7)
					grade += "+";
			}
		}
		cout << "The grade is " << grade << endl;
	}
	return 0;
}

注意:第17行score != 100很重要,要不然输入100会输出A++-的。

Exercise 5.6

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
    
    
	unsigned short score;
	while (cin >> score && score <= 100)
	{
    
    
		string grade;
		vector<string> vec{
    
     "F","D","C","B","A","A++" };
		grade = (score < 60) ? vec[0] : vec[(score - 50) / 10];
		grade += (score % 10 > 7) ? "+" : ((score % 10 < 3 && score != 100) ? "-" : "");
		cout << "The grade is " << grade << endl;
	}
	return 0;
}

虽然比5.5简洁,但可读性大大下降。

Exercise 5.9

#include <iostream>
using namespace std;

int main()
{
    
    
	char ch;
	unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
	while (cin >> ch)
	{
    
    
		if (ch == 'a') aCnt++;
		if (ch == 'e') eCnt++;
		if (ch == 'i') iCnt++;
		if (ch == 'o') oCnt++;
		if (ch == 'u') uCnt++;
	}
	cout << "The number of 'a' is " << aCnt << ".\n";
	cout << "The number of 'e' is " << eCnt << ".\n";
	cout << "The number of 'i' is " << iCnt << ".\n";
	cout << "The number of 'o' is " << oCnt << ".\n";
	cout << "The number of 'u' is " << uCnt << ".\n";
	return 0;
}

Exercise 5.10

Way I:

#include <iostream>
using namespace std;

int main()
{
    
    
	char ch;
	unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
	while (cin >> ch)
	{
    
    
		switch (ch)
		{
    
    
		    case 'a': case 'A':
			    ++aCnt;
			    break;
			case 'e': case 'E':
				++eCnt;
				break;
			case 'i': case 'I':
				++iCnt;
				break;
			case 'o': case 'O':
				++oCnt;
				break;
			case 'u': case 'U':
				++uCnt;
				break;
		}
	}
	cout << "The number of 'a' is " << aCnt << ".\n";
	cout << "The number of 'e' is " << eCnt << ".\n";
	cout << "The number of 'i' is " << iCnt << ".\n";
	cout << "The number of 'o' is " << oCnt << ".\n";
	cout << "The number of 'u' is " << uCnt << ".\n";
	return 0;
}

Way II:

#include <iostream>
using namespace std;

int main()
{
    
    
	char ch;
	unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0;
	while (cin >> ch)
	{
    
    
		ch = tolower(ch);
		switch (ch)
		{
    
    
		case 'a':
			++aCnt;
			break;
		case 'e':
			++eCnt;
			break;
		case 'i':
			++iCnt;
			break;
		case 'o':
			++oCnt;
			break;
		case 'u':
			++uCnt;
			break;
		}
	}
	cout << "The number of 'a' is " << aCnt << ".\n";
	cout << "The number of 'e' is " << eCnt << ".\n";
	cout << "The number of 'i' is " << iCnt << ".\n";
	cout << "The number of 'o' is " << oCnt << ".\n";
	cout << "The number of 'u' is " << uCnt << ".\n";
	return 0;
}

Exercise 5.11

注:此处若不使用 Line 8 的 noskipws 将无法达到目的。

#include <iostream>
using namespace std;

int main()
{
    
    
	char ch;
	unsigned aCnt = 0, eCnt = 0, iCnt = 0, oCnt = 0, uCnt = 0, spaceCnt = 0, tabCnt = 0, newlineCnt = 0;
	while (cin >> noskipws >> ch) // 'noskipws' means 'cin' doesn't omit space.
	{
    
    
		ch = tolower(ch);
		switch (ch)
		{
    
    
		case 'a':
			++aCnt;
			break;
		case 'e':
			++eCnt;
			break;
		case 'i':
			++iCnt;
			break;
		case 'o':
			++oCnt;
			break;
		case 'u':
			++uCnt;
			break;
		case ' ':
			++spaceCnt;
			break;
		case '\t':
			++tabCnt;
			break;
		case '\n':
			++newlineCnt;
			break;
		}
	}
	cout << "The number of 'a' is " << aCnt << ".\n";
	cout << "The number of 'e' is " << eCnt << ".\n";
	cout << "The number of 'i' is " << iCnt << ".\n";
	cout << "The number of 'o' is " << oCnt << ".\n";
	cout << "The number of 'u' is " << uCnt << ".\n";
	cout << "The number of Space is " << spaceCnt << ".\n";
	cout << "The number of Tab is " << tabCnt << ".\n";
	cout << "The number of Newline is " << newlineCnt << ".\n";
	return 0;
}

noskipws 详见 C++ Primer 17.5.1 (English Version Page 760)

Exercise 5.12

同样要用 noskipws。

#include <iostream>
using namespace std;

int main()
{
    
    
	char ch;
	char last_char = '0';
	unsigned ffCnt = 0, flCnt = 0, fiCnt = 0;
	while (cin >> noskipws >> ch) // 'noskipws' means 'cin' doesn't omit space.
	{
    
    
		if (last_char == 'f')
		{
    
    
			switch (ch)
			{
    
    
			case 'f':
				++ffCnt;
				break;
			case 'l':
				++flCnt;
				break;
			case 'i':
				++fiCnt;
				break;
			}
		}
		last_char = ch;
	}
	cout << "The number of 'ff' is " << ffCnt << ".\n";
	cout << "The number of 'fl' is " << flCnt << ".\n";
	cout << "The number of 'fi' is " << fiCnt << ".\n";
	return 0;
}

Exercise 5.14

程序及启示见我的博客 调试 C++ Primer Exercise 5.14 的心得体会

Exercise 5.17

开头部分解释详见我的博客 关于 C++中 输入多行不定数量数字 的思考

#include <iostream>
#include <vector>
#include <string>
#include <sstream> // std::istringstream
using namespace std;

int main()
{
    
    
	vector<int> vint1, vint2;
	string num1, num2;
	cout << " First vector:";
	getline(cin, num1);
	istringstream is1(num1);
	int i;
	while (is1 >> i)
		vint1.push_back(i);
	cout << "Second vector:";
	getline(cin, num2);
	istringstream is2(num2);
	int j;
	while (is2 >> j)
		vint2.push_back(j);
	bool result = 0;
	if (vint1 == vint2) result = 1;
	else
	{
    
    
		if (vint1.size() == vint2.size()) result = 0;
		else
		{
    
    
			if (vint1.size() > vint2.size()) exchange(vint1, vint2); // now vint1 is shorter than vint2
			unsigned s = 0;
			for (auto k = 0; k != vint1.size(); k++)
			{
    
    
				if (vint1[k] == vint2[k]) ++s;
			}
			if (s == vint1.size()) result = 1;
		}
	}
	if (!result)
		cout << "false" << endl;
	else cout << "true" << endl;
	return 0;
}

或者使用头文件 cinvec.h,见 关于 C++中 输入多行不定数量数字 的思考
关于编写头文件函数的一些心得见 调试 cinvec.h (C++头文件定义函数)的心得体会

#include <iostream>
#include <vector>
#include <string>
#include "cinvec.h"
using namespace std;

int main()
{
    
    
	string num1, num2;
	cout << " First vector:";
	vector<int>vint1 = cinvec_int(num1);
	cout << "Second vector:";
	vector<int>vint2 = cinvec_int(num2);
	bool result = 0;
	if (vint1 == vint2) result = 1;
	else
	{
    
    
		if (vint1.size() == vint2.size()) result = 0;
		else
		{
    
    
			if (vint1.size() > vint2.size()) exchange(vint1, vint2); // now vint1 is shorter than vint2
			unsigned s = 0;
			for (auto k = 0; k != vint1.size(); k++)
			{
    
    
				if (vint1[k] == vint2[k]) ++s;
			}
			if (s == vint1.size()) result = 1;
		}
	}
	if (!result)
		cout << "false" << endl;
	else cout << "true" << endl;
	return 0;
}

Exercise 5.19

#include <iostream>
#include <string>
using namespace std;

int main()
{
    
    
	string rsp;
	do
	{
    
    
		string str1, str2;
		cout << "Please enter two strings: ";
		cin >> str1 >> str2;
		string result = (str1 == str2) ? ("equal to ") : ((str1 > str2) ? "greater than " : "smaller than ");
		cout << str1 << " is " << result << str2 << "\nMore? Enter yes(Y) or no(N): ";
		cin >> rsp;
	} while (!rsp.empty() && rsp[0] != 'n' && rsp[0] != 'N');
	return 0;
}

Exercise 5.20

#include <iostream>
#include <string>
using namespace std;

int main()
{
    
    
	string word_now;
	string word_last = "";
	string word_final = "";
	while (cin >> word_now)
	{
    
    
		if (word_now == word_last)
		{
    
    
			word_final = word_now;
			break;
		}
		else word_last = word_now;
	}
	if (word_final.empty()) cout << "No word was repeated." << endl;
	else cout << word_final << " repeats twice." << endl;
	return 0;
}

Exercise 5.21

#include <iostream>
#include <string>
using namespace std;

int main()
{
    
    
	string word_now;
	string word_last = "";
	string word_final = "";
	while (cin >> word_now)
	{
    
    
		if (islower(word_now[0]) || !isalpha(word_now[0]))
		{
    
    
			word_last = word_now;
			continue;
		}
		if (word_now == word_last)
		{
    
    
			word_final = word_now;
			break;
		}
		else word_last = word_now;
	}
	if (word_final.empty()) cout << "No word was repeated." << endl;
	else cout << word_final << " repeats twice." << endl;
	return 0;
}

Exercise 5.22

do
{
    
    
    int sz = get_size();
}
while (sz <= 0);

Exercise 5.23

#include <iostream>
using namespace std;

int main()
{
    
    
	int a1, a2;
	cin >> a1 >> a2;
	double quotient = static_cast<double>(a1) / a2;
	cout << quotient << endl;
	return 0;
}

Example 1:

6 2

Output:

3


Example 2:

5 3

Output:

1.66667


Example 3:

2 0

Output:

inf


Example 4:

0 0

Output:

-nan(ind)


Example 5:

-3 0

Output:

-inf


Exercise 5.24

Error!

Exercise 5.25

#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

int main()
{
    
    
	int a1, a2;
	while (cin >> a1 >> a2)
	{
    
    
		try
		{
    
    
			if (a2 == 0) throw runtime_error("Divisor cannot be zero!");
			double quotient = static_cast<double>(a1) / a2;
			cout << quotient << endl;
		}
		catch (runtime_error err)
		{
    
    
			cout << err.what() << "\nTry Again? Enter yes(Y) or no(N)." << endl;
			string c;
			cin >> c;
			if (!cin || c[0] == 'n' || c[0] == 'N')
				break;
		}
	}
	return 0;
}

Input & Output:
Test

Next Chapter

【C++ Primer(5th Edition) Exercise】练习程序 - Chapter6(第六章)

猜你喜欢

转载自blog.csdn.net/weixin_50012998/article/details/108268626