C++Primer第五版 习题答案 【第六章】

C++Primer第五版 习题答案 【总目录】:https://blog.csdn.net/Dust_Evc/article/details/114334124

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; 

6.3

#include <iostream>

int fact(int i)
{
	return i > 1 ? i * fact(i - 1) : 1;
}

int main()
{
	std::cout << fact(5) << std::endl;
	return 0;
}

6.4

#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

unsigned main()
{
	void interactive_fact();
	interactive_fact();

	string Repeat = "是否重复本程序? y/n";
	cout << Repeat << endl;

	char C = ' ';
	while (cin >> C && C == 'y')
	{
		interactive_fact();
		cout << Repeat << endl;
	}

	return 0;
}

void interactive_fact()
{
	unsigned num = 0, mul = 1;
	cout << "请输入一个1到20之间的数字:";
	cin >> num;

	string out_of_range = "该数字不在范围内!请重新输入:";
	while (num < 1 || num >20)
	{
		cout << out_of_range;
		cin >> num;
	}
	while (num > 0)
		mul *= num--;

	cout << "该数字的阶乘为:" << mul << endl;
}

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

**形参**定义在函数形参列表里面;

**局部变量**定义在代码块里面;

**局部静态变量**在程序的执行路径第一次经过对象定义语句时初始化,并且直到程序终止时才被销毁。

6.7

int generate()
{
    static int ctr = 0;
    return ctr++;
}

6.8

Chapter6.h

#pragma once

#ifndef HEADER_H
#define HEADER_H
#include <iostream>
#include <string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

void interactive_fact(); 
#endif // !HEADER_H

6.9

fact.cpp

#include"Chapter6.h"

void interactive_fact()
{
	unsigned num = 0, mul = 1;
	cout << "请输入一个1到20之间的数字:" ;
	cin >> num;

	string out_of_range = "该数字不在范围内!请重新输入:";
	while (num < 1 || num >20)
	{
		cout << out_of_range;
		cin >> num;
	}
	while (num > 0)
		mul *= num--;
	
	cout << "该数字的阶乘为:" << mul << endl;
}

factMain.cpp

#include"Chapter6.h"

unsigned main()
{
	interactive_fact();

	string Repeat = "是否重复本程序? y/n";
	cout << Repeat << endl;

	char C = ' ';
	while (cin>>C && C == 'y')
	{
		interactive_fact();
		cout << Repeat << endl;
	}
	
	return 0;
}

6.10

6.11

扫描二维码关注公众号,回复: 12761825 查看本文章

6.40

 (a) 正确。
 (b) 错误。因为一旦某个形参被赋予了默认值,那么它之后的形参都必须要有默认值。

6.41

 (a) 非法。第一个参数不是默认参数,最少需要一个实参。
 (b) 合法。
 (c) 合法,但与初衷不符。字符 `*` 被解释成 `int` 传入到了第二个参数。而初衷是要传给第三个参数。

6.42

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::endl;

string make_plural(size_t ctr, const string& word, const string& ending = "s")
{
	return (ctr > 1) ? word + ending : word;
}

int main()
{
	cout << "singual: " << make_plural(1, "success", "es") << " "
		<< make_plural(1, "failure") << endl;
	cout << "plural : " << make_plural(2, "success", "es") << " "
		<< make_plural(2, "failure") << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/Dust_Evc/article/details/114271410