C++ Primer 第五版 課後章節練習答案 第五章

本文程序爲自己學習C++過程中編寫,文章給出需要自己編寫程序的課後習題解答,如有問題或錯誤歡迎交流指正,共同學習。

編譯軟件爲 vs2015。

第五章

練習5.1:

什麼是空語句?什麼時候會用到空語句?

解答: 

只含有一個單獨的分號的語句就是空語句。如果在程序的某個地方,語法上需要一條語句但是邏輯上不需要,此時應該使用空語句。

練習5.2:

什麼是塊?什麼時候會用到塊?

解答:

複合語句也被稱作塊,是指用花括號括起來的(可能爲空的)語句和聲明的序列。如果在程序的某個地方,語法上需要一條語句,但是邏輯上需要多條語句,就會用到塊。 

練習5.3:

使用逗號運算符(參見 4.10 節,第 140 頁)重寫 1.4.1 節(第 10 頁)的 while 循環,使它不再需要塊,觀察改寫之後的代碼的可讀性提高了還是降低了。

解答:

#include "stdafx.h"
#include<iostream>
using std::cout;
using std::endl;

int main()
{
	int sum = 0, val = 1;
	//只要 val 的值小於 1, while 循環的值就會持續執行
	while (val <= 10)
		sum += val, ++val;
	cout << "Sum of 1 to 10 inclusive is " << sum << endl;
    return 0;
}

用逗號運算符分隔開塊內的各條語句,以不再需要塊。但這種改寫方式降低了代碼的可讀性,同時逗號運算符總是輸出右側的運算結果,在本程序中雖然沒有影響,但不保證這種方式會在其他程序中有丟失數據的風險。 

練習5.4:

說明下列例子的含義,如果存在問題,試着修改它。

(a)while (string::iterator iter != s.end){ /*......*/ } 

(b)while (bool status = find(word)){ /*......*/ }

        if ( !status ){ /*......*/ }

解答:

(a)迭代器 iter 沒有初始化,修改:while (string::iterator iter = s.begin(), iter != s.end()){ /*......*/ };

(b)定義在控制結構當中的變量旨在相應語句的內部可見,一旦語句結束,變量就超出作用範圍。此時 status 在 if 語句中相當於未定義的變量,修改:while (bool status = find(word)){ /*......*/ ;  if ( !status ){ /*......*/ } }//將 if 語句放在 while 循環中。

練習5.5:

寫一段自己的程序,使用 if else 語句實現把數字成績轉換成字母成績的要求。

解答: 

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
using std::string;
using std::vector;
using std::cin;
using std::cout;
using std::endl;

int main()
{
	int grade = 0;
	const vector<string> vec = { "F","D","C","B","A","A++" };
	cout << " please input your grade: " << endl;
	while (cin >> grade) {
		string final;
		if (grade < 60)
			final = vec[0];
		else {
			final = vec[(grade - 50) / 10];
			if (grade != 100) { //注意100除以10餘數爲0但要避免在其後面添加減號
				if (grade % 10 >= 3) {
					if (grade % 10 > 7)
						final += "+";
				}
				else
					final += "-";
			}
		}
		cout << final << endl;
		cout << " please input your grade: " << endl;
	}
    return 0;
}

檢驗結果:

練習5.6:

改寫上一題的程序,使用條件運算符(參見第 4.7 節,第 134 頁)代替 if else 語句。

解答:

#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int main()
{
	int grade = 0;
	const vector<string> vec = { "F","D","C","B","A","A++" };
	string final;
	cout << " please input your grade: " << endl;
	while (cin >> grade) {
		final = grade < 60 ? vec[0] ://判斷分數段是否小於 60
			(grade == 100) ? vec[(grade - 50) / 10] :
			(grade % 10 > 7) ? (vec[(grade - 50) / 10] + "+"):
			(grade % 10 < 3) ? (vec[(grade - 50) / 10] + "-"):
			vec[(grade - 50) / 10];
		cout << final << endl;
		cout << " please input your grade: " << endl;
	}
    return 0;
}

驗證結果:

練習5.7:

改正下列代碼段中的錯誤。

(a)if ( ival1 != ival2 )

          ival1 = ival2

         else ival1 = ival2 = 0;

(b)if ( ival < minval )

           minval = ival;

           occurs = 1;

(c)if ( int ival ) = get_value() ) 

          cout << "ival = " << ival << endl;

          if ( !ival )

          cout << "ival = 0\n";

(d)if ( ival = 0)

           ival = get_value( );

解答:

(a)第二行沒有加分號。

修改:if ( ival1 != ival2 )

               ival1 = ival2;

                else ival1 = ival2 = 0;

(b)if 中包含多條語句,需要用花括號括起來,容易產生歧義。

修改: if ( ival < minval ) {

                  minval = ival;

                occurs = 1;}

(c)在第二條 if 語句中,變量 ival 是指未定義的,需要在條件語句外定義 ival,使其作用範圍爲整個程序。

修改:int ival;

            if ( int ival ) = get_value() ) 

                   cout << "ival = " << ival << endl;

             if ( !ival )

                    cout << "ival = 0\n";

(d)判斷是否相等運算符爲 "==",此處使用的是賦值運算符,條件語句的執行結果永遠是 false。

修改:if ( ival == 0)

            ival = get_value( );

練習5.8:

什麼是「懸垂 else」?C++ 語言是如何處理 else 子句的?

解答:

當 if 語句內部嵌套多個 if 語句時,很可能 if 分支多於 else 分支,如何確定給定的 else 與某個 if 匹配成爲懸垂 else。C++ 中規定 else 與其相鄰最近的未匹配的 if 匹配,消除了程序的二義性。

練習5.9: 

編寫一段程序,使用一系列 if 語句統計從 cin 讀入的文本中有多少元音字母。

解答:

#include "stdafx.h"
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
using std::endl;

int main()
{
	char ch;
	unsigned acnt = 0, ecnt = 0, icnt = 0, ocnt = 0, ucnt = 0;
	cout << "Please input words: " << endl;
	while (cin >> ch) {
		if (ch == 'a')
			++acnt;
	        if (ch == 'e')
			++ecnt;
		if (ch == 'i')
			++icnt;
		if (ch == 'o')
			++ocnt;
		if (ch == 'u')
			++ucnt;
	}
	cout << "Number of vowel a: \t" << acnt << endl;
	cout << "Number of vowel e: \t" << ecnt << endl;
	cout << "Number of vowel i: \t" << icnt << endl;
	cout << "Number of vowel o: \t" << ocnt << endl;
	cout << "Number of vowel u: \t" << ucnt << endl;
    return 0;
}

 

練習5.10:

我們之前實現的統計元音字母的程序存在一個問題:如果元音字母以大寫形式出現,不會被統計在內。編寫一段程序,統計元音字母的小寫形式,也統計大寫形式,也就是說,新程序遇到 'a' 和 'A' 都應該遞增 acnt 的值,以此類推。

解答:

#include "stdafx.h"
#include<iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
	char ch;
	unsigned acnt = 0, ecnt = 0, icnt = 0, ocnt = 0, ucnt = 0;
	cout << "please input your words: " << endl;
	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 << "Number of vowel a or A: \t" << acnt << endl;
	cout << "Number of vowel e or E: \t" << ecnt << endl;
	cout << "Number of vowel i or I: \t" << icnt << endl;
	cout << "Number of vowel o or O: \t" << ocnt << endl;
	cout << "Number of vowel u or U: \t" << ucnt << endl;
    return 0;
}