C++ Primer(第五版) 第六章练习答案

C++ Primer(第五版) 第六章练习答案

6.1



/**
 * 形参出现在函数定义中
 * 实参出现在主调函数中
 */

6.2



/**
 * a
 * 返回类型不匹配
 * int 改为 string
 * 
 * b
 * 没有返回类型 加 void
 * 
 * c
 * 形参同名 v1 改 v2
 * 
 * d
 * 函数体没有花括号 { }
 */

6.3

#include <iostream>
using std::cout; using std::endl;

int fact(int val)
{
   
    int ret = 1;
    while (val)
        ret *= val--;

    return ret;
}


int main()
{
   
    cout << fact(5) << endl;

    return 0;
}

6.4

#include <iostream>
using std::cout; using std::endl; using std::cin;

int fact()
{
   
    int val;
    int ret = 1;

    cin >> val;

    if (val > 0)
        while (val)
            ret *= val--;
    else if (val < 0)
        while (val)
            ret *= val++;
    else
        return 0;
    
    return ret;
}


int main()
{
   
    cout << fact() << endl;

    return 0;
}

6.5

#include <iostream>
using std::cout; using std::endl; using std::cin;

int absolute(int x)
{
   
    if (x >= 0)
        return x;
    return -x;
}


int main()
{
   
    int x;
    while (cin >> x)
        cout << absolute(x) << endl;

    return 0;
}

6.6

//        形参 必须有初始值
int func(int x)
{
   
    // 自动变量 可以没有初始值, 执行默认初始化
    int y;
    // 局部静态变量 可以没有初始值, 执行值初始化, 不会被销毁
    static int z;

    return ++z;
}

6.7

#include <stdio.h>

int func() {
    static int x; return x++; }

int main()
{
   
    for (int i = 0; i < 10; ++i)
        printf("%d\n", func());

    return 0;
}

6.8


int fact(int val);

int fact();

int absolute(int x)

6.9cc

#include "6_9.h"

int func()
{
      
    static int x;

    return ++x;
}

6.9h

#ifndef _6_9_h
#define _6_9_h

int func();

#endif

6.9cpp

#include <iostream>
#include "6_9.h"

int main()
{
   
    std::cout << func() << std::endl;

    return 0;
}

6.10

#include <iostream>

using namespace std;

// 初始化一个非引用的变量时, 初始值被拷贝给变量
void func(int *x, int *y);

int main()
{
   
    int n = 10, m = 20;

    func(&n, &m);

    cout << n << " " <<  m << endl;

    return 0;
}

void func(int *x, int *y)
{
   
    int p = *x;
    *x = *y;
    *y = p;
}

6.11

#include <iostream>

using namespace std;

void reset(int &x);

int main()
{
   
    int x = 30;
    reset(x);

    cout << x 
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值