[C++ Primer Plus] 第7章、函数(一)程序清单——递归,指针和const,指针数组和数组指针,函数和二维数组

程序清单7.6

#include<iostream>
using namespace std;

const int Size = 8;
int sum_arr(int arr[], int n);//函数声明
void main()
{
    int cookies[Size] = { 1,2,4,8,16,32,64,128 };
    cout << cookies << " =array address," << sizeof cookies << " =sizeof cookies" << endl;
    int sum = sum_arr(cookies, Size);
    cout << "Total cookies eaten: " << sum << endl;
    sum = sum_arr(cookies, 3);
    cout << "First three eaters ate " << sum << endl;
    sum = sum_arr(cookies+4,4);
    cout << "Last four eaters ate " << sum << endl;

    system("pause");
}

int sum_arr(int arr[], int n)//输出地址,大小,计算和
{
    int total = 0;
    cout << arr << " =arr," << sizeof(arr) << " =sizeof(arr)" << endl;
    for (int i = 0; i <n; i++)
        total += arr[i];
    return total;
}

指针和const

const的位置不同,指针可以进行的操作也不同

 

month数组被const修饰了,所以如果要使用sum函数的话,需要修改第四行代码

int sum(const int arr[],int n)

函数和二维数组

先修知识:指针数组和数组指针

#include <iostream>
using namespace std;

int main()
{
    int c[4] = { 1,2,3,4 };
    int *a[4]; //指针数组
    int(*b)[4]; //数组指针
    b = &c;
    for (int i = 0; i<4; i++)//将数组c中元素赋给数组a
    {
        a[i] = &c[i];
    }
    cout << *a[1] << endl; //输出2就对
    cout << (*b)[2] << endl; //输出3就对
    return 0;
}

OK,进入正题,函数与二维数组

#include<iostream>
using namespace std;

//数组表示法
int sum(int arr[][4], int n)
{
    int total = 0;
    for (int r = 0; r < n; r++)
    {
        for (int c = 0; c < 4; c++)
        {
            cout << arr[r][c] << "	";
            total += arr[r][c];
        }
        cout << endl;
    }
    return total;
}

//指针表示法
int sum2(int (*arr)[4],int n)//数组指针:指向数组的指针
{
    int total = 0;
    for (int r = 0; r < n; r++)
    {
        for (int c = 0; c < 4; c++)
        {
            cout << *(*(arr+r)+c)<< "	";//arr是一个指向数组(4个int整数)的指针,*(arr+r)=arr[r]表示指向第(r+1)个数组
            total += *(*(arr + r) + c);
        }
        cout << endl;
    }
    return total;
}

void main()
{
    int data[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };
    int s = sum(data, 3);
    cout << s << endl;
    getchar();
}


 程序清单7.11

#include<iostream>
using namespace std;

const int Rate = 60;
struct time {
    int hour;
    int mins;
};

time sum(time a, time b) {
    time total;
    total.hour = a.hour + b.hour + (a.mins + b.mins) / Rate;
    total.mins = (a.mins + b.mins) % 60;
    return total;
}
void show(time t) {
    cout << t.hour << " hours," << t.mins << " minutes." << endl;
}

void main()
{
    time d1 = { 5,45 };
    time d2 = { 4,55 };
    time trip = sum(d1, d2);
    cout << "Two_day total:";
    show(trip);
    
    time d3 = { 4,32 };
    cout << "Three_day total:";
    show(sum(trip, d3));

    getchar();
}

 程序清单7.12+7.13

#include<iostream>
#include<cmath>
using namespace std;

struct polar{
    double distance;
    double angle;
};
struct rect {
    double x;
    double y;
};

void rect_to_polar(const rect *pxy, polar *pda) {//由于形参是指针而不是结构,所以只能用箭头操作符而不能用点操作符
    pda->distance = sqrt( pxy->x*pxy->x + pxy->y*pxy->y );
    pda->angle = atan2(pxy->y, pxy->x);
}
void show(const polar *pda) {
    const double Rate = 57.29577951;
    cout << "distance=" << pda->distance;
    cout << ",angle=" << pda->angle*Rate<<" degrees"<<endl;
}

void main()
{
    rect r;
    polar p;
    cout << "Enter the x and y value:";
    while (cin>>r.x>>r.y)
    {
        rect_to_polar(&r, &p);
        show(&p);
        cout << "Next 2 numbers(q to quit):";
    }
    cout << "Done." << endl;
    getchar();
}

程序清单7.14(string对象数组)

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

const int Size = 5;
void display(const string s[],int n) {
    for (int i = 0; i < n; i++)
        cout << i+1 <<": "<<s[i]<<endl;
}

void main()
{
    string list[Size];
    cout << "Enter your " << Size << " favorite XX" << endl;
    for (int i = 0; i < Size; i++)
    {
        cout << i + 1 << ": ";
        getline(cin, list[i]);//读取string对象
    }
    cout << "Your list:" << endl;
    display(list, Size);
    system("pause");
}

程序清单7.15(array对象)

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

const array<string, 4> Sname = { "Spring","Summer","Fall","Winter" };


void fill(array<double, 4> *p) {
    for (int i = 0; i < 4; i++)
    {
        cout << "Enter " << Sname[i] << " expenses:";
        cin >> (*p)[i];//p是地址,*p是array对象,(*p)[i]是array对象里的第(i+1)个double数据
    }
}
void show(array<double, 4> q) {
    double sum = 0.0;
    cout << "EXPENSES" << endl;
    for (int i = 0; i < 4; i++)
    {
        cout << Sname[i] << ": $" << q[i] << endl;
        sum += q[i];
    }
    cout << "Sum expenses: $" << sum << endl;
}

void main()
{
    array<double, 4> expense;
    fill(&expense);
    show(expense);
    system("pause");
}

程序清单7.16,7.17(递归)

#include<iostream>
using namespace std;

void down(int n) {
    cout << "Counting down " << n <<",	n at "<<&n<< endl;
    if (n > 0)
        down(n - 1);
    cout << n << ": Kaboom!" << "		n at " << &n << endl;
}

void main()
{
    down(4);
    system("pause");
}

#include<iostream>
using namespace std;

const int Len = 66;
const int Div = 6;
void subdivide(char ar[],int low,int high,int level) {
    if (level == 0)
        return;
    int mid = (high + low) / 2;
    ar[mid] = '|';
    subdivide(ar, low, mid, level - 1);
    subdivide(ar, mid, high,level - 1);
}

void main()
{
    char ruler[Len];
    int i;
    for (i = 1; i < Len - 2; i++)//去掉一个头,两个尾
        ruler[i] = ' ';
    ruler[Len - 1] = '';//末尾设置为结束符
    int max = Len - 2;//倒数第二位(去掉结束符后的末尾)
    int min = 0;
    ruler[min] = ruler[max] = '|';
    cout << ruler << endl;
    for (i = 1; i <=Div; i++)
    {
        subdivide(ruler, min, max, i);
        cout << ruler << endl;
    }
    system("pause");
}


函数指针

double (*pf)(int);//pf是一个指向函数(函数返回double)的指针
double *pd(int);//pd()是一个返回double *的函数

函数声明  

void aa(int n, double(*pf)(int));

指出,pf是一个函数指针,它指向的函数接受一个int参数,并返回一个double值。

  aa(50,函数名)    即可进行调用。

 程序清单7.18

#include<iostream>
using namespace std;

void estimate(int line,double (*pf)(int)) {
    cout << line << " lines will take ";
    cout << (*pf)(line) << " hour(s)." << endl;
}
double bet(int lns) {
    return 0.05*lns;
}
double pam(int lns) {
    return 0.03*lns + 0.0004*lns*lns;;
}

void main()
{
    int code;
    cout << "How many lines? ";
    cin >> code;
    cout << "Here is Bet's estimate:" << endl;
    estimate(code, bet);
    cout << "Here is Pam's estimate:" << endl;
    estimate(code, pam);
    system("pause");
}

函数指针数组

const double * f1(const double ar[], int n);
const double * f2(const double [], int);
const double * f3(const double *, int);//这三行代码的含义完全相同
const double *(*pa[3])(const double *, int) = { f1,f2,f3 };//声明,并初始化

*pd[3]        //an array of 3 pointers
(*pd)[3]      //a pointer to an array of 3 elements

程序清单7.19

 1 #include<iostream>
 2 using namespace std;
 3 
 4 const double * f1(const double *ar, int n) {    //f1()是一个返回double类型指针的函数
 5     return ar;//返回的是地址,要得到值得话,必须加上*符号
 6 }
 7 const double * f2(const double ar[], int n) {
 8     return ar + 1;
 9 }
10 const double * f3(const double ar[], int n) {
11     return ar + 2;
12 }
13 
14 void main()
15 {
16     double av[3] = { 1112.3,1542.6,2227.9 };
17     const double *(*p1)(const double *, int) = f1;//p1是函数指针,指向f1函数的地址,*p1(即f1函数)传入double地址和int长度,返回double地址
18     auto p2 = f2;
19     cout << "Using pointers to functions:" << endl << "Address Value" << endl;
20     cout << (*p1)(av, 3) << ": " << *(*p1)(av, 3) << endl;//*p1表示函数,前者调用函数,返回double值得地址,后者为取出地址所代表的的double值
21     cout << p2(av, 3) << ": " << *p2(av, 3) << endl;//p2表示函数
22 
23     const double *(*pa[3])(const double *, int) = { f1,f2,f3 };//声明一个函数指针数组
24     auto pb = pa;//pa表示函数指针数组的地址
25     cout << "Using an array of pointers to functions:" << endl << "Address Value" << endl;
26     for (int i = 0; i < 3; i++)
27         cout << pa[i](av, 3) << ": " << *pa[i](av, 3) << endl;
28     cout << "Using a pointer to a pointer to a functions:" << endl << "Address Value" << endl;
29     for (int i = 0; i < 3; i++)
30         cout << pb[i](av, 3) << ": " << *pb[i](av, 3) << endl;
31 
32     cout << "Using pointers to an array of pointers :" << endl << "Address Value" << endl;
33     auto pc = &pa;
34     cout << (*pc)[0](av, 3) << ": " << *(*pc)[0](av, 3) << endl;
35     const double *(*(*pd)[3])(const double *, int) = &pa;//参见23行,pd表示pa的地址,所以在23行定义的基础上再多一个*号
36     const double * pdb = (*pd)[1](av, 3);//(*pd)=pa,pdb表示av[1]的地址
37     cout << pdb << ": " << *pdb << endl;
38     cout << (*(*pd)[2])(av, 3) << ": " << *(*(*pd)[2])(av, 3) << endl;//(*pd)=pa,(*(*pd)[2])=(*pa[2])表示函数指针数组的第三个指针元素
39 
40     system("pause");
41 }

 

原文地址:https://www.cnblogs.com/little-monkey/p/7531077.html