C++ Primer 第六章答案

练习6.1在函数调用,参数传递中,实参将内容复制给形参。作用域:实参的作用域要大于形参,形参仅在被调用的函数中使用。练习6.2(a) int f() { // -> string f() string s; // ... return s; }(b) void f2(int i) { /* ... */ } ...
摘要由CSDN通过智能技术生成

练习6.1
在函数调用,参数传递中,实参将内容复制给形参。
作用域:实参的作用域要大于形参,形参仅在被调用的函数中使用。

练习6.2
(a) int f() { // -> 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>
#include <vector>

using namespace std;

int fact(int val)
{
    if (val == 1)
        return 1;
    else
        return val*fact(val-1);
}

int main() 
{
    int a = 3, b = 0;
    b = fact(a);
    cout << b << endl;
    system("pause");
    return 0;
}

练习6.4
#include <iostream>
#include <vector>

using namespace std;

int fact(int val)
{
    if (val == 1)
        return 1;
    else
        return val*fact(val-1);
}

int main() 
{
    int a = 0, b = 0;
    cout << "Please input number" << endl;
    cin >> a;
    b = fact(a);
    cout << b << endl;
    system("pause");
    return 0;
}

练习6.5
#include <iostream>
#include <vector>

using namespace std;

int abs(int val)
{
    return (val >= 0) ? val : -val;
}

int main() 
{
    int a = 0, b = 0;
    cout << "Please input number" << endl;
    cin >> a;
    b = abs(a);
    cout << b << endl;
    system("pause");
    return 0;
}

练习6.6
形参与普通的局部变量作用域等性质基本相同,唯一一点不同是形参的初始化
时是由实参赋值完成,而局部静态变量的作用域只存在于局部但生命
周期是在整个程序中都存在。
#include <iostream>
#include <vector>

using namespace std;

int static_test(int val)
{
    static int a = 0;
    a += val;
    return a;
}

int main() 
{
    int a = 0;
    cout << "Please input number" << endl;
    while(cin >> a) 
        cout <<  static_test(a) << endl;
    
    system("pause");
    return 0;
}

练习6.7
#include <iostream>
#include <vector>

using namespace std;

int test()
{
    static int a = 0;
    return a++;
}

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值