C++Primer 第五版 习题答案 第六章 函数

这篇博客详细解答了C++ Primer第五版第六章关于函数的习题,涉及形参、实参、局部变量、引用、常量引用、函数重载等多个核心概念,并探讨了函数参数传递的方式及其影响。
摘要由CSDN通过智能技术生成

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值