《C++ Primer》第五版课后习题解答_第六章(2)(08-15)

来源:互联网 发布:如何追妹子知乎 编辑:程序博客网 时间:2024/06/07 17:59

系统环境: windows 10 1703

编译环境:Visual studio 2017


6.8

#pragma once#include <iostream>int adamfact(int val);int fact(int fac1);double Adamabs(double abs1);

6.9

Chapter6.h

//见题目 6.8
fact.cc

#include <iostream>#include "chapter6.h"int adamfact(int val){    int ret = 1;    while (val > 1)    {        ret *= val--;    }    return ret;}int fact(int fac1) // 构建计算阶乘的 fact 函数  {    int sum = 1;    if (fac1 == 0) // 判断输入实参的值,如果是 0,返回 1(0! = 1)      {        sum = 1;    }    else    {        while (fac1 != 0) // 如果不是零,则计算阶乘          {            sum *= fac1;            --fac1;        }    }    return sum; // 返回函数计算结果  }double Adamabs(double abs1){    return abs(abs1);}
factMain.cc
#include <iostream>#include "chapter6.h"using std::cout;using std::cin;using std::endl;using std::runtime_error;int main(){    cout << adamfact(5) << endl;    cout << fact(5) << endl;    cout << Adamabs(-5) << endl;    return 0;}
输出为:

120

120

5


6.10

函数:AdamSwap

#include "AdamSwap.h"double AdamSwap(double *i, double *j){    *i = *j + *i;    *j = *i - *j;    *i = *i - *j;    return *i, *j;}
主函数:

#include "AdamSwap.h"#include <iostream>using std::cout;using std::endl;using std::cin;int main(){    double a = 0, b = 0;    cout << "Input two numbers: " << endl;    cin >> a >> b;    (a, b) = AdamSwap(&a, &b);    cout << "a: " << a << " b: " << b << endl;    return 0;}
输入:

5.6 3.5

输出:

a: 3.5 b: 5.6 


6.11

头文件:

#pragma once#include <iostream>int reset(int &a);

reset 函数:

#include "reset.h"int reset(int &a){    a = 0;    return a;}
主调函数:

#include "reset.h"using std::cout;using std::endl;int main(){    int a = 5;    a = reset(a);    cout << a << endl;    return 0;}

6.12

#include "AdamSwap.h"double AdamSwap(double &i, double &j){    i = j + i;    j = i - j;    i = i - j;    return i, j;}
我觉得使用引用更易于使用。因为引用对象可以直接被使用,从而达到改变实参的效果。而使用指针的话,还需要进行解引用操作才能改变实参的值。


6.13

void f(T)

T 是形参,其和给其传值的实参是两个相互独立的对象;

void f(&T)

在这里形参是引用类型,则此引用形参和给它传值的实参绑定。即此引用形参也是它绑定的对象的别名。改变形参的值


6.14

应该是引用类型:

//如题 6.11 中 reset 函数
不能是引用类型:

这道题没做出来,参考 Mooophy/Cpp-Primer 得到如下函数:

void print(std::vector<int>::iterator begin, std::vector<int>::iterator end){        for (std::vector<int>::iterator iter = begin; iter != end; ++iter)                std::cout << *iter << std::endl;}

6.15

(1) s 为常量引用。因为 s 有可能是一个很大的字符串,为了避免拷贝 s 所造成的降低效率,故将其设为引用类型。又因为给它传值的实参无需修改其值,故将 s 设为常量引用;

(2) c 为 char 类型。因为函数中需要一个字符类型的形参,且字符类型所占空间很小,再加上给它传值的实参的值无需做出改变。综合考虑,把 c 的类型设定成 char 而不是 引用类型;

(3) 如果 s 为普通引用,则其值(以及和其绑定的实参的值)在函数中有可能被改变;

(4) 如果 occurs 为常量引用,则其值不能被改变,语句 occurs = 0,和 ++occurs 都成了非法语句。

阅读全文
0 0