《C++ Primer Plus》第七章习题与参考答案

1,内容选自《C++ Primer Plus》(第6版)中文版,2017年1月河北第21次印刷版本
2,文章系笔者学习笔记,若有错误,欢迎指正
3,如有雷同,纯属巧合

7.12 复习题

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();// or void igor(void)
b.float tofu(int i);// or float tofu(int)
c.double mpg(double d1, double d2);
d.long summation(long array[]; int size);
e.double doctor(const char * str);
f.void ofcourse(boss b);
g.char * plot(map *pmap);

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

void set_array(int arr[], int size, int value)
{
  for (int i = 0; i < size; i++)
    arr[i] = value;
}

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

void set_array(int *begin, int *end, int value)
{
  for (int *pt = begin; pt != end; pt++)
    *pt = value;
}

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

double get_max(const double arr[], int size)
{
  double max;
  if (size < 1)
  {
    cout << "Invalid array size of " << size << endl;
    cout << "Returning a value of 0\n";
    return 0;
  }
  else
  {
    max = arr[0];
    for (int i = 0; i < max; i++)
    {
      if (arr[i] > max)
        max = arr[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. 按值传递结构
void display(applicant app)
{
  cout << app.name << endl;
  for (int i = 0; i < 3; i++)
    cout << app.credit_ratings[i] << endl;
}
// b. 按地址传递结构
void show(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 application *a1, const application *a1);

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

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

7.13 编程练习

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

#include <iostream>
using namespace std;
double harmean(double x, double y);

int main()
{
  cout << "Please enter two numbers, until one of the numbers is 0: ";
  double x, y, result;
  cin >> x >> y;
  while (x != 0 && y != 0)
  {
    result = harmean(x, y);
    cout << "the harmean is:" << result << endl;
    cout << "Please enter two numbers, until one of the numbers is 0: ";
    cin >> x >> y;
  }
  cout << "Done." << endl;
  return 0;
}

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

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

#include <iostream>
using namespace std;
const int MAX = 10;
int fill_array(double ar[], int limit);
void show_array(double ar[], int n);
double calculate_array(double ar[], int n);

int main()
{
  double golf[MAX];
  int size = fill_array(golf, MAX);
  if (size > 0)
  {
    show_array(golf, size);
    calculate_array(golf, size);
  }
  else
  {
    cout << "There is no golf performance. \n";
  }
  cout << "Done. \n";
  return 0;
}

int fill_array(double ar[], int limit)
{
  double temp;
  int i;
  for (i = 0; i < limit; i++)
  {
    cout << "Enter golf performance #" << (i + 1) << ": ";
    cin >> temp;
    if (!cin)
    {
      cin.clear();
      while (cin.get() != '\n')
      {
        continue;
      }
      cout << "Bad input; ipput proces terminated. \n";
      break;
    }
    else if (temp < 0)
    {
      break;
    }
    ar[i] = temp;
  }
  return i;
}

void show_array(double ar[], int n)
{
  cout << "golf results are: ";
  for (int i = 0; i < n; i++)
  {
    cout << ar[i] << " ";
  }
  cout << endl;
}

double calculate_array(double ar[], int n)
{
  double sum, average;
  for (int i = 0; i < n; i++)
  {
    sum += ar[i];
  }
  average = sum / n;
  cout << "golf average is: " << average << endl;
  return average;
}

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 show(box b)
{
  cout << "maker:" << b.maker << " "
       << "height:" << b.height << " "
       << "width:" << b.width << " "
       << "length:" << b.length << " "
       << "volume:" << b.volume << endl;
}

void set_volume(box *b)
{
  b->volume = b->height * b->width * b->length;
}

int main()
{
  box b = {"tupper", 1, 2, 3};
  set_volume(&b);
  show(b);
  return 0;
}

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

#include <iostream>
using namespace std;
long double probability(unsigned numbers, unsigned picks);

int main()
{
  long double pro_field = probability(47, 5);
  long double pro_special = probability(27, 1);
  long double result = pro_field * pro_special;
  cout << result << endl;
  system("PAUSE");
  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 * n / p;
  }
  return result;
}

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

#include <iostream>
using namespace std;
int factorial(unsigned int number);

int main()
{
  int number;
  long long fact;
  cout << "Please enter a number for factorial:";
  while (cin >> number)
  {
    fact = factorial(number);
    cout << number << "!=" << fact << endl;
    cout << "Please enter a number for factorial:";
  }
  return 0;
}

int factorial(unsigned int number)
{
  int result;
  if (number == 0 || number == 1)
  {
    result = 1;
  }
  else
  {
    result = number * factorial(number - 1);
  }
  return result;
}

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

#include <iostream>
using namespace std;
int Fill_array(double array[], int size);
void Show_array(const double array[], int size);
void Reverse_array(double array[], int size);

int main()
{
  double array[5];
  cout << "Fill array:" << endl;
  Fill_array(array, 5);
  Show_array(array, 5);
  Reverse_array(array, 5);
  cout << "Reverse array" << endl;
  Show_array(array, 5);
  Reverse_array(array + 1, 3);
  cout << "Reverse array, except the first and the last one:" << endl;
  Show_array(array, 5);
  return 0;
}

int Fill_array(double array[], int size)
{
  cout << "Please enter double value:";
  int i = 0;
  while (size && cin >> array[i])
  {
    i++, size--;
    if (size != 0)
      cout << "Please enter double value:";
  }
  cout << "total numbers is:" << i << endl;
}

void Show_array(const double array[], int size)
{
  cout << "current array:";
  for (int i = 0; i < size; i++)
  {
    cout << array[i] << " ";
  }
  cout << endl;
}

void Reverse_array(double array[], int size)
{
  double temp;
  for (int i = 0; i < size / 2; i++)
  {
    temp = array[i];
    array[i] = array[size - i - 1];
    array[size - i - 1] = temp;
  }
}

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

#include <iostream>
const int Max = 5;
double *fill_array(double *begin, double *end);
void show_array(double *begin, double *end);
void revalue(double r, double *begin, double *end);

int main()
{
  using namespace std;
  double properties[Max];
  double *end = fill_array(properties, properties + Max - 1);
  show_array(properties, end);
  cout << "Enter revaluation factor:";
  double factor;
  while (!(cin >> factor))
  {
    cin.clear();
    while (cin.get() != '\n')
    {
      continue;
    }
    cout << "Bad input: input process terminated. \n";
  }
  revalue(factor, properties, end);
  show_array(properties, end);
  cout << "Done.\n";
  return 0;
}

double *fill_array(double *begin, double *end)
{
  using namespace std;
  double *p;
  int i = 0;
  for (p = begin; p <= end; p++)
  {
    cout << "Enter value #" << (i + 1) << ": ";
    if (!(cin >> *p))
    {
      cin.clear();
      while (cin.get() != '\n')
      {
        continue;
      }
      cout << "Bad input: input process terminated. \n";
      break;
    }
    i++;
  }
  return (p - 1);
}

void show_array(double *begin, double *end)
{
  using namespace std;
  double *p;
  int i = 0;
  for (p = begin; p <= end; p++)
  {
    cout << "Property #" << (i + 1) << ": $";
    cout << *p << endl;
    i++;
  }
}

void revalue(double r, double *begin, double *end)
{
  double *p;
  for (p = begin; p <= end; p++)
  {
    (*p) *= r;
  }
}

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

// a
#include <iostream>
const int Seasons = 4;
const char *Snames[] = {"Spring", "Summer", "Fall", "Winter"};
void fill(double *p);
void show(double *p);

int main()
{
  double expenses[Seasons] = {};
  fill(expenses);
  show(expenses);
  return 0;
}

void fill(double *p)
{
  using namespace std;
  for (int i = 0; i < Seasons; i++)
  {
    cout << "Enter " << Snames[i] << " expenses: ";
    cin >> p[i];
  }
}

void show(double *p)
{
  using namespace std;
  double total = 0.0;
  cout << "EXPENSES\n";
  for (int i = 0; i < Seasons; i++)
  {
    cout << Snames[i] << " :$" << p[i] << endl;
    total += p[i];
  }
  cout << "Total Expenses: $" << total << endl;
}

// b
#include <iostream>
const int Seasons = 4;
const char *Snames[] = {"Spring", "Summer", "Fall", "Winter"};
struct expenses
{
  double expen[Seasons];
};
void fill(expenses *e);
void show(const expenses *e);

int main()
{
  expenses e;
  fill(&e);
  show(&e);
  return 0;
}

void fill(expenses *e)
{
  using namespace std;
  for (int i = 0; i < Seasons; i++)
  {
    cout << "Enter " << Snames[i] << " expenses: ";
    cin >> e->expen[i];
  }
}

void show(const expenses *e)
{
  using namespace std;
  double total = 0.0;
  cout << "EXPENSES\n";
  for (int i = 0; i < Seasons; i++)
  {
    cout << Snames[i] << " :$" << e->expen[i] << endl;
    total += e->expen[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;
};
int getinfo(student pa[], int n);
void display1(student st);
void display2(const student *ps);
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 result = 0;
  for (int i = 1; i <= n; i++)
  {
    cout << "student #" << i << ": " << endl;
    cout << "fullname: ";
    cin.getline(pa[i].fullname, SLEN);
    if (pa[i].fullname[0] == '\0') //判断空行
      break;
    cout << "hobby: ";
    cin.getline(pa[i].hobby, SLEN);
    cout << "ooplevel: ";
    (cin >> pa[i].ooplevel).get();
    //本循环会给下一个循环留一个回车读取到fullname,所以调用cin.get()读取到这个回车键,这样就不会给下fullname.
    ++result;
  }
  cout << "Enter End.\n";
  return result;
}

void display1(student st)
{
  cout << "display1:\n";
  cout << "fullname:" << st.fullname << " hobby:" << st.hobby << " ooplevel:" << st.ooplevel << endl;
}

void display2(const student *ps)
{
  cout << "display2:\n";
  cout << "fullname:" << ps->fullname << " hobby:" << ps->hobby << " ooplevel:" << ps->ooplevel << endl;
}

void display3(const student pa[], int n)
{
  cout << "display3:\n";
  for (int i = 0; i < n; i++)
  {
    cout << "fullname:" << pa[i].fullname << " hobby:" << pa[i].hobby << " ooplevel:" << 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()调用这些函数。提示:下面是声明这种指针数组的方式,其中包含三个指针:
double (pf[3])(double, double);
可以采用数组初始化语法,并将函数名作为地址来初始化这样的数组。

#include <iostream>
using namespace std;
double add(double, double);
double subtract(double, double);
double multiply(double, double);
double divide(double, double);
double calculate(double, double, double (*pf)(double, double));
const int SIZE = 4;
int main()
{

  double (*pf[SIZE])(double, double) = {add, subtract, multiply, divide};
  double x, y;
  cout << "Please enter two numbers <q to quit>: " << endl;
  while (cin >> x >> y)
  {
    for (int i = 0; i < SIZE; i++)
    {
      double q = calculate(x, y, pf[i]);
      cout << q << " ";
    }
    cout << "\nPlease enter two numbers <q to quit>: " << endl;
  }
  return 0;
}

double calculate(double x, double y, double (*pf)(double, double))
{
  double result;
  result = pf(x, y);
  return result;
}

double add(double x, double y)
{
  return x + y;
}
double subtract(double x, double y)
{
  return x - y;
}
double multiply(double x, double y)
{
  return x * y;
}

double divide(double x, double y)
{
  return x / y;
}

发布了8 篇原创文章 · 获赞 1 · 访问量 683

猜你喜欢

转载自blog.csdn.net/Heisenberg_Li/article/details/104040248