《C++ Primer》5th 課後練習 第六章 函數 1~10

練習 6.1 實參和形參的區別的什麼?
實參是調用函數時實際傳入的值,是形參的初始值。
練習 6.2 請指出下列函數哪個有錯誤,爲什麼?應該如何修改這些錯誤呢?

(a) int f() {
          string s;
          // ...
          return s;
    }
(b) f2(int i) { /* ... */ }
(c) int calc(int v1, int v1)  /* ... */ }
(d) double square (double x)  return x * x; 

修改:

//(a) 返回類型與函數聲明類型不一致
	string f() {
          string s;
          // ...
          return s;
    }
//(b) 沒有聲明函數類型
	void f2(int i) { /* ... */ }
//(c) 少個{
	int calc(int v1, int v1) { /* ... */ }
//(d) 缺少{}
	double square (double x) { return x * x;} 

練習 6.3 編寫你自己的fact函數,上機檢查是否正確。

int fact(int num) {
	if (num == 0) return 1;
	return num * fact(num - 1);
}

練習 6.4 編寫一個與用戶交互的函數,要求用戶輸入一個數字,計算生成該數字的階乘。在main函數中調用該函數。

#include<iostream>
#include<string>
using namespace std;
int fact(int num) {
	if (num == 0) return 1;
	return num * fact(num - 1);
}
void inter() {
	int n;
	while (true) {
		cout << "Enter a num: " << endl;
		cin >> n;
		try {
			if (n < 0 || n >12)
				throw range_error("out of range");
				cout << fact(n) << endl;
		}
		catch(range_error err){
			cout << err.what() << "\nTry Again? Enter y or n" << endl;
			char c;
			cin >> c;
			if (c == 'n')
				break;
		}
		
	}
}
int main()
{
	inter();
	return 0;
}

練習 6.5 編寫一個函數輸出其實參的絕對值。

#include <iostream>
int abs(int i)
{
    return i > 0 ? i : -i;
}
int main()
{
    std::cout << abs(-5) << std::endl;
    return 0;
}

練習 6.6 說明形參、局部變量以及局部靜態變量的區別。編寫一個函數,同時達到這三種形式。

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

int count_iter(int a) {//a是形參,b是局部變量,s是靜態局部變量
	static int s = 0;
	int b = 0;
	++b;++s;
	cout << "a: " << a << endl;
	cout << "s: " << s << endl;
	cout << "b: " << b << endl;
	return b + s + a;
}
int main()
{
	for (int k = 0; k < 10; ++k)
		cout << count_iter(k) << endl;
	return 0;
}

練習 6.7 編寫一個函數,當它第一次被調用時返回0,以後每次被調用返回值加1。

int count_iter() {
	static int s = -1;
	return ++s;
}

練習 6.8 編寫一個名爲Chapter6.h 的頭文件,令其包含6.1節練習中的函數聲明。

int count_iter();

練習 6.9 編寫你自己的fact.cc 和factMain.cc ,這兩個文件都應該包含上一小節的練習中編寫的 Chapter6.h 頭文件。通過這些文件,理解你的編譯器是如何支持分離式編譯的。

//main.c
#include<iostream>
#include"func.h"
using namespace std;
int main()
{
	for (int k = 0; k < 10; ++k)
		cout << count_iter() << endl;
	return 0;
}
//func.h
int count_iter();
//func.c
#include"func.h"

int count_iter() {
	static int s = -1;
	return ++s;
}

練習 6.10 編寫一個函數,使用指針形參交換兩個整數的值。在代碼中調用該函數並輸出交換後的結果,以此驗證函數的正確性。

#include<iostream>
using namespace std;
void swap(int *a, int *b) {
	int tmp = *a;
	*a = *b;
	*b = tmp;
	return;
}

int main()
{
	int a = 1, b = 2;
	cout << "a: " << a << "\nb: " << b << endl;
	swap(&a, &b);
	cout << "a: " << a << "\nb: " << b << endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章