C++程序设计Y.Daniel Liang 第八、九章课后习题答案

更新时间:2023-10-08 04:18:02 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

Exercise8_2

#include using namespace std;

long fib(int n) {

int f0 = 0, f1 = 1, currentFib;

if (n == 0) return 0; if (n == 1) return 1;

for (int i = 1; i <= n; i++) { currentFib = f0+f1; f0 = f1;

f1 = currentFib; }

return f1; }

int main() {

cout << \

return 0; }

Exercise8_4

#include using namespace std;

double m(int i) {

if (i == 1) return 1; else

return m(i - 1) + 1.0 / i; }

int main() {

for (int i = 1; i <= 10; i++) cout << m(i) << endl;

return 0; }

Exercise8_6

#include using namespace std;

double m(int i) {

if (i == 1)

return 1.0 / 2; else

return m(i - 1) + i * 1.0 / (i + 1); }

int main() {

for (int i = 1; i <= 10; i++)

cout << \

return 0; }

Exercise8_8

#include using namespace std;

void reverseDisplay(int value) {

if (value != 0) {

cout << value % 10; value = value / 10; reverseDisplay(value); } }

int main() {

reverseDisplay(123456);

return 0; }

Exercise8_10

#include using namespace std;

char * substring(const char * const s, int start, int end) {

char * pNewString = new char[end - start + 1 + 1];

int j = 0;

for (int i = start; i <= end; i++, j++) {

pNewString[j] = s[i]; }

pNewString[j] = '\\0'; // Set a null terminator

return pNewString; }

int count(const char * const s, char a) {

int result = 0; if (strlen(s) > 0)

result = count(substring(s, 1, strlen(s) - 1), a) + ((s[0] == a) ? 1 : 0);

return result; }

int main() {

cout << count(\

return 0; }

Exercise8_12

#include using namespace std;

void reverseDisplay(const char * const s, int high) {

if (high > 0) {

cout << s[high];

reverseDisplay(s, high - 1); }

}

void reverseDisplay(const char * const s, int high) {

if (high > 0) {

cout << s[high];

reverseDisplay(s, high - 1); } }

int main() {

reverseDisplay(\

return 0; }

Exercise8_14

#include using namespace std;

int countUppercase(char * s, int high) {

if (high == 0)

return isupper(s[0]) ? 1 : 0; else

return countUppercase(s, high - 1) + (isupper(s[high]) ? 1 : 0); }

int countUppercase(char * s) {

return countUppercase(s, strlen(s) - 1); }

int main() {

int list[] = {

1, 2, 3, 4, 5 };

cout << countUppercase(\

return 0; }

Exercise8_16

#include using namespace std;

int countMoves = 0;

/* The function for finding the solution to move n disks from fromTower to toTower with auxTower */

void moveDisks(int n, char fromTower, char toTower, char auxTower) {

countMoves++;

if (n == 1) // Stopping condition

cout << \ else {

moveDisks(n - 1, fromTower, auxTower, toTower);

cout << \ moveDisks(n - 1, auxTower, toTower, fromTower); } }

int main() {

// Read number of disks, n

cout << \ int n; cin >> n;

// Find the solution recursively cout << \ moveDisks(n, 'A', 'B', 'C');

cout << \

return 0; }

Exercise9_2

#include using namespace std;

本文来源:https://www.bwwdw.com/article/9vud.html

Top