《C++ Primer Plus》第七章课后题

复习题

1.使用函数的3个步骤是什么?

这3个步骤是定义函数、提供原型、调用函数。

2.请创建与下面的描述匹配的函数原型。

a. igor()没有参数,且没有返回值。
b. tofu()接受一个int参数,并返回一个float。
c.mpg()接受两个double 参数,并返回一个double。
d.summation()将long数组名和数组长度作为参数,并返回一个long值。
e. doctor()接受一个字符串参数(不能修改该字符串),并返回一个double 值。
f. ofcourse()将boss 结构作为参数,不返回值。
g. plot()将map结构的指针作为参数,并返回一个字符串。

a. void igor(void);
b. float tofu(int);
c. double mpg(double,double);
d. long summation(long [],int);
e. double doctor(const string);
f.  void ofcourse(boss);
g. string plot(map*);

3. 编写一个接受3个参数的函数:int数组名、数组长度和一个int值,并将数组的所有元素都设置为该int值。

void setin(int arr[],int n,int a)
{
        for(int i=0;i<n;i++)
                arr[i]=a;
}

4. 编写一个接受3个参数的函数:指向数组区间中第一个元素的指针、指向数组区间最后一个元素后面的指针以及一个int值,并将数组中的每个元素都设置为该int值。

void setin(int* begin,int* end,int a)
{
        for(int* p=begin;p!=end;p++)
                *p=a;
}

5. 编写将 double 数组名和数组长度作为参数,并返回该数组中最大值的函数。该函数不应修改数组的内容。

double biggest(const double d[],int n)
{
        double max;
        if(size<2)
        {
                cout << "Invalid array size of " << size << endl;
                cout << "Returning a value of on";
                return 0;
        }
        else
        {
                max=d[0];
                for(int i=0;i<n;i++)
                        if(d[i]>max)
                                max=d[i];
                return max;
        }
}

6.为什么不对类型为基本类型的函数参数使用const限定符?

将const 限定符用于指针,以防止指向的原始数据被修改。程序传递基本类型(如int或double)
时,它将按值传递,以便函数使用副本。这样,原始数据将得到保护。

7.C++程序可使用哪3种C-风格字符串格式?

字符串可以存储在char 数组中,可以用带双引号的字符串来表示,也可以用指向字符串第一个字符的指针来表示。

8.编写一个函数,其原型如下:

int replace(char * str, char c1, char c2);
该函数将字符串中所有的c1都替换为c2,并返回替换次数。

int replace(char * str, char c1, char c2)
{
        int count=0;
        while(*str)
        {
                if(*str==c1)
                {
                        *str=c2;
                        count++;
                }
                str++;
        }
        return count;
}

9. 表达式*"pizza"的含义是什么?"taco”[2]呢?

由于C++将“pizza”解释为其第一个元素的地址,因此使用*运算符将得到第一个元素的值,即字符p。由于C++将“taco”解释为第一个元素的地址;因此它将“taco”[2]解释为第二个元素的值,即字符c。换句话来说,字符串常量的行为与数组名相同。

10. C++允许按值传递结构,也允许传递结构的地址。如果glitz是一个结构变量,如何按值传递它?如何传递它的地址?这两种方法有何利弊?

要按值传递它,只要传递结构名glitz.即可。要传递它的地址,使用地址运算符&glitz。按值传递将自动保护原始数据,但这是以时间和内存为代价的。按地址传递可节省时间和内存,但不能保护原始数据,除非对函数参数使用了const 限定符。另外,按值传递意味着可以使用常规的结构成员表示法,但传递指针则必须使用间接成员运算符。

11. 函数judge()的返回类型为int,它将这样一个函数的地址作为参数:将const char指针作为参数,并返回一个int值。请编写judge()函数的原型。

int judge (int (*pf) (const char *));

12. 假设有如下结构声明:

struct applicant

{

        char name [30];
        int credit_ratings [3];

};

a. 编写一个函数,它将application结构作为参数,并显示该结构的内容。
b. 编写一个函数,它将application结构的地址作为参数,并显示该参数指向的结构的内容。

a. 注意,如果ap是一个applicant结构,则ap.credit_ratings就是一个数组名,而 ap.credit_ratings[i]是一个数组元素:
void display (applicant ap)
{
        cout << ap.name << endl;
        for (int i = 0; i < 3; i++)
                cout << ap.credit_ratings[i] << endl;
}
b. 注意,如果 pa 是一个指向 applicant 结构的指针,则 pa->credit_ratings 就是一个数组名,而
pa->credit_ratings[i]是一个数组元素:
void show(const applicant * pa)
{
        cout << pa->name << endl;
        for (int i = 0; i < 3; i++)
                cout << pa->credit_ratings[i] << endl;
}

13. 假设函数f1()和f2()的原型如下:

void f1(applicant * a);
const char * f2(const applicant * al, const applicant *a2);

请将p1和p2分别声明为指向f1和f2的指针;将ap声明为一个数组,它包含5个类型与p1相同的指针;将pa声明为一个指针,它指向的数组包含10个类型与p2相同的指针。使用typedef来帮助完成这项工作。

typedef void (*p_f1) (applicant *);
p_f1 p1=f1;
typedef const char * (*p_f2) (const applicant *, const applicant *);
p_f2 p2=f2;
p_f1 ap[5];
p_f2 (*pa)[10];

编程练习

1. 编写一个程序,不断要求用户输入两个数,直到其中的一个为0。对于每两个数,程序将使用一个函数来计算它们的调和平均数,并将结果返回给main(),而后者将报告结果。调和平均数指的是倒数平均值的倒数,计算公式如下:调和平均数=2.0*x*y/(x+y)

#include <iostream>
using namespace std;

double calculate(double x, double y) 
{
    return 2.0*x*y/(x+y);
}

int main()
{
    double x=1, y=1;
    cout<<"请输入两个数的值:";
    while(cin>>x>>y&&x!=0&&y!=0)
    {
        cout<<"调和平均数为:"<<calculate(x,y)<<endl;
        cout<<"请继续输入两个数的值:";
    }
    return 0;
}

2. 编写一个程序,要求用户输入最多10个高尔夫成绩,并将其存储在一个数组中。程序允许用户提早结束输入,并在一行上显示所有成绩,然后报告平均成绩。请使用3个数组处理函数来分别进行输入、显示和计算平均成绩。

#include <iostream>
using namespace std;
double grade[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
void set_grade(void);
void display_grade(void);
void calculate_grade(void);
int main()
{
    set_grade();
    display_grade();
    calculate_grade();
    return 0;
}

void set_grade(void)
{
    for (int i = 0; i < 10; i++)
    {
        cout << "Enter the grade of " << i + 1 << " subject: ";
        if (cin >> grade[i])
        {
        }
        else
        {
            grade[i] = -1;
            break;
        }
    }
    return;
}

void display_grade(void)
{
    cout << "The grades are: ";
    for (int i = 0; grade[i] != -1&&i<10; i++)
        cout << grade[i] << " ";
    cout << endl;
    return;
}

void calculate_grade(void)
{
    double sum = 0;
    for (int i = 0; grade[i] != -1&&i<10; i++)
    {
        sum += grade[i];
    }
    cout << "The average grade is: " << sum / 10 << endl;
    return;
}

3. 下面是一个结构声明:

struct box

{

        char maker [40];
        float height;
        float width;
        float length;
        float volume;

}

a. 编写一个函数,按值传递box结构,并显示每个成员的值。
b. 编写一个函数,传递box结构的地址,并将volume成员设置为其他三维长度的乘积。
c. 编写一个使用这两个函数的简单程序。

#include <iostream>
using namespace std;
struct box
{
char maker [40];
float height;
float width;
float length;
float volume;
};
void display(box b);
void set_volume(box* b);
int main()
{
    box b={"abcd",1.1,2,3,4.4};
    display(b);
    set_volume(&b);
    return 0;
}
void display(box b)
{
    cout<<b.maker<<endl;
    cout<<b.height<<endl;
    cout<<b.width<<endl;
    cout<<b.length<<endl;
    cout<<b.volume<<endl;
}
void set_volume(box* b)
{
    b->volume=b->height*b->width*b->length;
}

4.许多州的彩票发行机构都使用如程序所示的简单彩票玩法的变体。在这些玩法中,玩家从一组被称为域号码(field number)的号码中选择几个。例如,可以从域号码1~47中选择5个号码;还可以从第二个区间(如1~27)选择一个号码(称为特选号码)。要赢得头奖,必须正确猜中所有的号码。中头奖的几率是选中所有域号码的几率与选中特选号码几率的乘积。例如,在这个例子中,中头奖的几率是从47个号码中正确选取5个号码的几率与从27个号码中正确选择1个号码的几率的乘积。请修改程序,以计算中得这种彩票头奖的几率。

#include <iostream>
using namespace std;
// Note: some implementations require double instead of long double
long double probability(unsigned numbers, unsigned picks);
int main()
{
	cout<<"从47个域号码中选取5个并在第二个区间27个中选取一个的概率为:";
    cout<<probability(47,5)*probability(27,1)<<endl;
	return 0;
}

long double probability(unsigned numbers, unsigned picks)
{
	long double result = 1.0;
	long double n;
	unsigned p;
	for (n = numbers, p = picks; p > 0; n--, p--)
		result = result * p / n;
	return result;
}

5. 定义一个递归函数,接受一个整数参数,并返回该参数的阶乘。前面讲过,3的阶乘写作3!,等于3*2!,依此类推;而0!被定义为1。通用的计算公式是,如果n大于零,则n != n*(n-1)!。在程序中对该函数进行测试,程序使用循环让用户输入不同的值,程序将报告这些值的阶乘。

#include <iostream>
using namespace std;

int func(int n);
int main()
{
	int n;
	cout<<"请输入一个数字:";
	while(cin>>n)
	{
		cout<<n<<"的阶乘为:";
		cout<<func(n)<<endl;
		cout<<"请继续输入一个数字:";
	}
	return 0;
}
int func(int n)
{
	if(n==1||n==0)
        return 1;
    else
        return n*func(n-1);
}

6. 编写一个程序,它使用下列函数:
Fill_array()将一个double数组的名称和长度作为参数。它提示用户输入double值,并将这些值存储到数组中。当数组被填满或用户输入了非数字时,输入将停止,并返回实际输入了多少个数字。
Show_array()将一个double数组的名称和长度作为参数,并显示该数组的内容。
Reverse-array()将一个double数组的名称和长度作为参数,并将存储在数组中的值的顺序反转。程序将使用这些函数来填充数组,然后显示数组;反转数组,然后显示数组;反转数组中除第一个和最后一个元素之外的所有元素,然后显示数组。

#include <iostream>
using namespace std;
int fill_array(double* d,int n);
void show_array(double* d,int n);
void reserve_array(double* d,int n);
int main()
{
	double d[10];
    int len=fill_array(d,10);
    show_array(d,len);
	reserve_array(d,len);
	show_array(d,len);
	reserve_array(d+1,len-2);
	show_array(d,len);
    return 0;
}


int fill_array(double* d,int n)
{
	cout<<"请输入数组元素:";
	int i;
	for(i=0;i<n&&cin>>d[i];i++)
	{
		cout<<"请继续输入:";
	}
	return i;
}
void show_array(double* d,int n)
{
	for(int i=0;i<n;i++)
    {
        cout<<d[i]<<" ";
    }
	cout<<endl;
}
void reserve_array(double* d,int n)
{
	for(int i=0;i<n/2;i++)
	{
		double temp=d[i];
        d[i]=d[n-i-1];
        d[n-i-1]=temp;
	}
}

7. 修改程序清单7.7中的3个数组处理函数,使之使用两个指针参数来表示区间。fill_array()函数不返回实际读取了多少个数字,而是返回一个指针,该指针指向最后被填充的位置;其他的函数可以将该指针作为第二个参数,以标识数据结尾。

#include <iostream>
using namespace std;
const int Max = 5;
double *fill_array(double *begin, double *end);
void show_array(double *begin, double *end); // don't change data
void revalue(double *begin, double *end,double r);
int main()
{
	double properties[Max];
	double *end = fill_array(properties, properties + Max);
	show_array(properties, end);
	cout << "Enter revaluation factor: ";
	double factor;
	while (!(cin >> factor))
	{
		cin.clear();
		while (cin.get() != '\n')
			continue;
		cout << "Bad input; Please enter a number: ";
	}
	revalue(properties, end,factor);
	show_array(properties, end);
	cout << "Done.\n";
	return 0;
}
double *fill_array(double *begin, double *end)
{
	double *now;
	int i;
	for (now = begin, i = 0; now != end; now++, i++)
	{
		cout << "Enter value #" << (i + 1) << ": ";
		if (!(cin >> *now))
		{
			cin.clear();
			while (cin.get() != '\n')
				continue;
			cout << "Bad input;input process terminated.\n";
			break;
		}
	}
	return now;
}
void show_array(double *begin, double *end)
{
	cout << "数组为:";
	for (double *i = begin; i != end; i++)
	{
		cout << *i << " ";
	}
	cout << endl;
}
void revalue(double *begin, double *end, double r)
{
	for (double *i = begin; i != end; i++)
		*i *= r;
}

8. 在不使用array类的情况下完成程序清单7.15所做的工作。编写两个这样的版本:
a. 使用const char*数组存储表示季度名称的字符串,并使用double数组存储开支。
b. 使用const char *数组存储表示季度名称的字符串,并使用一个结构,该结构只有一个成员——一个用于存储开支的double数组。这种设计与使用array类的基本设计类似。

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

const int Seasons = 4;
const char* Snames[4] =
    {"Spring", "Summer", "Fall", "Winter"};
void fill(double *);
void show(double *);
int main()
{
    double expenses[Seasons];
    fill(expenses);
    show(expenses);
    return 0;
}
void fill(double * d)
{
    using namespace std;
    for (int i = 0; i < Seasons; i++)
    {
        cout << "Enter " << Snames[i] << " expenses: ";
        cin >> d[i];
    }
}
void show(double * d)
{
    using namespace std;
    double total = 0.0;
    cout << "\nEXPENSES\n";
    for (int i = 0; i < Seasons; i++)
    {
        cout << Snames[i] << ": $" << d[i] << endl;
        total += d[i];
    }
    cout << "Total Expenses: $" << total << endl;
}
#include <iostream>
#include <string>
using namespace std;
const int Seasons = 4;
const char* Snames[4] =
    {"Spring", "Summer", "Fall", "Winter"};
struct Arr
{
	double ex[Seasons];
};
void fill(Arr*);
void show(Arr);
int main()
{
    Arr array1;
    fill(&array1);
    show(array1);
    return 0;
}
void fill(Arr* array)
{
    using namespace std;
    for (int i = 0; i < Seasons; i++)
    {
        cout << "Enter " << Snames[i] << " expenses: ";
        cin >> array->ex[i];
    }
}
void show(Arr array)
{
    using namespace std;
    double total = 0.0;
    cout << "\nEXPENSES\n";
    for (int i = 0; i < Seasons; i++)
    {
        cout << Snames[i] << ": $" << array.ex[i]<< endl;
        total += array.ex[i];
    }
    cout << "Total Expenses: $" << total << endl;
}

9. 这个练习让您编写处理数组和结构的函数。下面是程序的框架,请提供其中描述的函数,以完成该程序。

#include <iostream>
using namespace std;
const int SLEN = 30;
struct student
{
	char fullname[SLEN];
	char hobby[SLEN];
	int ooplevel;
};
// getinfo() has two arguments: a pointer to the first element of
// an array of student structures and an int representing the
// number of elements of the array. The function solicits and
// stores data about students. It terminates input upon filling
// the array or upon encountering a blank line for the student
// name. The function returns the actual number of array elements
// filled.
// getinfo() 函数有两个参数:一个指向学生结构数组第一个元素的指针,一个表示数组元素数量的 int。该函数通过询问学生数据并将其存储在数组中。当填充数组或在输入学生姓名时遇到空白行时,该函数将终止输入。该函数返回实际填充数组元素数量。
int getinfo(student pa[], int n);
// display1() takes a student structure as an argument
// and displays its contents
void display1(student st);
// display2() takes the address of student structure as an
// argument and displays the structure's contents
void display2(const student *ps);
// display3 () takes the address of the first element of an array
// of student structures and the number of array elements as
// arguments and displays the contents of the structures
void display3(const student pa[], int n);

int main()
{
	cout << "Enter class size: ";
	int class_size;
	cin >> class_size;
	while (cin.get() != '\n')
		continue;
	student *ptr_stu = new student[class_size];
	int entered = getinfo(ptr_stu, class_size);
	for (int i = 0; i < entered; i++)
	{
		display1(ptr_stu[i]);
		display2(&ptr_stu[i]);
	}
	display3(ptr_stu, entered);
	delete[] ptr_stu;
	cout << "Done\n";
	return 0;
}
int getinfo(student pa[], int n)
{
	int i = 0;
	while (i < n)
	{
		cout << "Enter student name: ";
		if (cin.getline(pa[i].fullname, SLEN)&&pa[i].fullname[0]=='\0')
		{
			cin.clear();
			break;
		}
		cout << "Enter hobby: ";
		if (cin.getline(pa[i].hobby, SLEN)&&pa[i].hobby[0]=='\0')
		{
			cin.clear();
			break;
		}
		cout << "Enter ooplevel: ";
		if (!(cin >> pa[i].ooplevel))
		{
			cin.clear();
			while (cin.get() != '\n')
				continue;
			break;
		}
		i++;
		while (cin.get() != '\n')
			continue;
	}
	return i;
}
void display1(student st)
{
	cout << "Student name: " << st.fullname << endl;
	cout << "Hobby: " << st.hobby << endl;
	cout << "OOP level: " << st.ooplevel << endl;
}
void display2(const student *ps)
{
	cout << "Student name: " << ps->fullname << endl;
	cout << "Hobby: " << ps->hobby << endl;
	cout << "OOP level: " << ps->ooplevel << endl;
}
void display3(const student pa[], int n)
{
	for (int i = 0; i < n; i++)
	{
		cout << "Student name: " << pa[i].fullname << endl;
		cout << "Hobby: " << pa[i].hobby << endl;
		cout << "OOP level: " << pa[i].ooplevel << endl;
	}
}

10. 设计一个名为calculate()的函数,它接受两个double值和一个指向函数的指针,而被指向的函数接受两个double参数,并返回一个double值。calculate()函数的类型也是double,并返回被指向的函数使用calculate()的两个double参数计算得到的值。例如,假设add()函数的定义如下:

double add(double x, double y)

{

    return x+y;

}

则下述代码中的函数调用将导致calculate()把2.5和10.4传递给add()函数,并返回add()的返回
值(12.9):
double q =calculate(2.5, 10.4, add);
请编写一个程序,它调用上述两个函数和至少另一个与add()类似的函数。该程序使用循环来让用户
成对地输入数字。对于每对数字,程序都使用calculate()来调用add()和至少一个其他的函数。如果读者爱冒险,可以尝试创建一个指针数组,其中的指针指向add()样式的函数,并编写一个循环,使用这些指针连续让calculate()调用这些函数。提示:下面是声明这种指针数组的方式,其中包含三个指针:
doubIe (*pf [3]}(double, double};可以采用数组初始化语法,并将函数名作为地址来初始化这样的数组。

#include <iostream>
using namespace std;

double calculate(double x, double y, double (*f)(double,double)) ;
double add1(double x, double y);
double add2(double x, double y);
double add3(double x, double y);
int main()
{
	double x,y;
	double (*p[3])(double,double)={add1,add2,add3};
	while(cin>>x>>y)
	{
		for(int i=0;i<3;i++)
        {
            cout<<calculate(x,y,p[i])<<endl;
        }
	}
	return 0;
}
double calculate(double x, double y, double (*f)(double,double))
{
	return f(x,y);
}
double add1(double x, double y)
{
	return x+y;
}
double add2(double x, double y)
{
	return 2*x+2*y;
}
double add3(double x, double y)
{
	return 3*x+3*y;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值