6.1
形参在函数声明中定义
实参是形参的初始值
6.2
a)返回类型错误,应改为 string
string f()
{
string s;
//...
return s;
}
b)应该加上函数声明
void f2(int i){
/**/}
c) 形参的名字不能相同
int calc(int v1,int v2)
{
/* */
}
d)需要花括号(块)
double square(double x)
{
return x*x;
}
6.3
#include<iostream>
int fact(int i)
{
int res = 1;
while (i>1)
{
res *= i--;
}
return res;
}
int main()
{
int j =fact(5);
std::cout << j << std::endl;
return 0;
}
6.4
#include<iostream>
int fact(int i)
{
int res = 1;
while (i>1)
{
res *= i--;
}
return res;
}
int main()
{
std::cout << "input a intNum" << std::endl;
int n;
std::cin >> n;
std::cout << fact(n) << std::endl;
return 0;
}
6.5
#include<iostream>
int absolute(int i)
{
return (i > 0) ? i : (-i);
}
int main()
{
std::cout << absolute(-2) << std::endl;
}
6.6
形参是局部变量的一种
形参和函数体内部定义的变量称为局部变量
局部静态变量的生命周期贯穿函数调用以及之后的周期
size_t count_call(int n)
{
static size_t ctr =0;
ctr+=n;
return ctr;
}
int main()
{
for(size_t i =0;i<10;++i)
cout <<count_call(i)<<endl;
return 0;
}
6.7
size_t count_call()
{
static size_t ctr =0;
return ++ctr;
}
6.8
#ifndef CHAPTER6.h
#define CHAPTER6.h
int fact(int n);
int absolute(int n);
#endif
6.9
fact.cpp
#include "Chapter6.h"
int fact(int n)
{
int ret = 1;
for(int i = 1;i <= n;++i)
{
ret *= i;
}
return ret;
}
int absolute(int n)
{
return (n > 0) ? n : -n;
}
factMain.cpp
#include <iostream>
#include "Chapter6.h"
int main()
{
std::cout << fact(5) << std::endl;
return 0;
}
6.10
#include<iostream>
using std::cout;
using std::endl;
void swap(int * i,int *j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}
int main()
{
int i = 1, j = 2;
cout << "i=" << i << " j=" << j