练习 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;
}