C++ Primer 从入门到放弃 之 第六章 练习题

6.1

6.1 节练习

#include <iostream>
using namespace std;

double square(double x){
   
    return x * x;
}

int fact(int i){
   
    int ret = 1;
    for (;i != 1; --i) ret *= i; 
    return ret;
}

double abs(double i){
   
    if (i >= 0) return i;
    else return -i;
}

int main(){
   

    // 6.1
    // 在函数初始化的时候需要定义形参和形参的类型
    // 在函数调用的时候需要传入对应类型的实参

    // 6.2
    // a 函数定义的返回值为int,却返回了string
    // b 没有定义返回值的类型,可以改为 void fi(int i) { /.../ }
    // c 两个形参的命名不能相同
    // d 没错吧
    cout << square(3.14) << endl;

    // 6.3
    cout << fact(5) << endl;

    // 6.4
    cout << "Please input an integer: ";
    int input;
    cin >> input;
    cout << "the fact of " << input << " is: " << fact(input) << endl;

    // 6.5
    cout << "Please input a number: ";
    double input2;
    cin >> input2;
    cout << "the abs of " << input2 << " is: " << abs(input2) << endl;

    return 0;
}

6.1.1 节练习

#include <iostream>
using namespace std;

int threeType(int a){
   
    int res;
    static int allTime = 0;
    ++allTime;
    return allTime;
}

int count(){
   
    static int time = 0;
    ++time;
    return time;
}

int main(){
   

    // 6.6
    // 形参是一种局部变量,他只能在作用域内被查看
    // 局部静态变量是在第一次被访问时初始化,程序结束时才被销毁,函数的结束对他并没有影响
    threeType(1);

    // 6.7
    for (int i = 0; i != 10; ++i){
   
        cout << count() << endl;
    }

    return 0;
}

6.1.2 节练习

int threeType(int a);
int count();

6.2

6.2.1 节练习

#include <iostream>
#include <vector>
#include <string>
using namespace std;

void change(int *p1, int *p2){
   
    int tmp = *p1;
    *p1 = *p2;
    *p2 = tmp;
    return;
}

int main(){
   
    int a = 1, b = 2;
    cout << a << " " << b << endl;
    change(&a,&b);
    cout << a << " " << b << endl;
    return 0;
}

6.2.2 节练习

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void reset(int &i){
   
    i = 0;
}

void swap(int &i, int &j){
   
    int tmp = i;
    i = j;
    j = tmp;
}

int main(){
   

    // 6.11
    int i = 10;
    cout << i << endl;
    reset(i);
    cout << i << endl;

    // 6.12
    int m = 1, n = 11;
    cout <<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值