您的位置:首页 > 编程语言 > C语言/C++

C++ primer Plus(第六版)中文版 第七章 函数——C++的编程模块 编程练习答案

2019-01-01 16:03 417 查看

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

[code]#include <iostream>

double get_harmonic_mean(double x, double y);

int main()
{
    using namespace std;
    
    double x, y;
    double harmonic_mean;
    
    cout << "请输入两个由空白隔开的数字:\n";
    while (cin>>x>>y)
    {
        if (x == 0 || y == 0)
            break;
        else
        {
            harmonic_mean = get_harmonic_mean(x, y);
            cout << x << "与" << y << "的调和平均数为:" <<  harmonic_mean << endl;
        }
    }
    cout << "end";
    return 0;
}

double get_harmonic_mean(double x, double y)
{
    double z;
    z = 2.0*x*y/(x+y);
    return z;
}

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

2.1 版本1

[code]#include <iostream>

int input(double grades[], int times);
double calculate_average(const double grades[], int times);
void show(const double grades[], int times, double average);

int main()
{
    using namespace std;
    
    int times = 10;
    double* grades = new double [times];
    double average;
    
    times = input(grades, times);

    
    average = calculate_average(grades, times);
    
    show(grades, times, average);

    
    return 0;
}

int input(double grades[], int times)
{
    using namespace std;
    double grade;
    int real_times = 0;
    cout << "请输入最多10个高尔夫成绩:\n";

    for (int i = 0; i < times; i++)
    {
        if(cin >> grade)
        {
           grades[i] = grade;
           real_times++;
        }
        else
            break;
    }
    return times = real_times;
}    

double calculate_average(const double grades[], int times)
{
    double average;
    double sum = 0;
    for (int i = 0; i < times; i++)
        sum = sum + grades[i];
    average = sum/times;
    return average;
}

void show(const double grades[], int times, double average)
{
    using namespace std;
    cout << "输入的高尔夫成绩为:\n";
    for (int i = 0; i < times; i++)
        cout << grades[i] << "\t";
    cout << endl << times << "次的平均成绩为:" << average;
}

2.2 版本2,函数之间调用

[code]#include <iostream>

void input(double grades[], int times);
void calculate_average(const double grades[], int times);
void show(const double grades[], int times, double average);

int main()
{
    const int times = 10;
    double grades[times];
    
    input(grades, times);
    
    return 0;
}

void input(double grades[], int times)
{
    using namespace std;
    double grade;
    int real_times = 0;
    cout << "请输入最多10个高尔夫成绩:\n";

    for (int i = 0; i < times; i++)
    {
        if(cin >> grade)
        {
           grades[i] = grade;
           real_times++;
        }
        else
            break;
    }
    calculate_average(grades, real_times);
}    

void calculate_average(const double grades[], int times)
{
    double average;
    double sum = 0;
    for (int i = 0; i < times; i++)
        sum = sum + grades[i];
    average = sum/times;
    show(grades, times, average);
}

void show(const double grades[], int times, double average)
{
    using namespace std;
    cout << "输入的高尔夫成绩为:\n";
    for (int i = 0; i < times; i++)
        cout << grades[i] << "\t";
    cout << endl << times << "次的平均成绩为:" << average;
}

3. 下面是一个结构声明
struct box
{
    char maker[40];
    float height;
    float width;
    float length;
    float volume;
};
a. 编写一个函数,按值传递box结构,并显示每一个成员的值
b. 编写一个函数,传递box结构的地址,并将volume成员设置为其他三维长度的乘积
c. 编写一个使用这两个函数的简单程序

[code]#include <iostream>

struct box
{
    char maker[40];
    float height;
    float width;
    float length;
    float volume;
};

void input_calculate(box*);
void show(box);

int main()
{
    box object;
    
    input_calculate(&object);
    show(object);
    
    return 0;
}

void input_calculate(box* point)
{
    using namespace std;
    cout << "请输入高度:";
    cin >> point->height;
    cout << "请输入宽度:";
    cin >> point->width;
    cout << "请输入长度:";
    cin >> point->length;
    point->volume = point->height * point->width * point->length;
}

void show(box value)
{
    using namespace std;
    cout << "高度:" << value.height << endl;
    cout << "宽度:" << value.width << endl;
    cout << "长度:" << value.length << endl;
    cout << "体积:" << value.volume << endl;
}

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

[code]// lotto.cpp -- probability of winning
#include <iostream>
// Note: some implementations require double instead of long double
long double probability(unsigned numbers, unsigned picks);
int main()
{
    using namespace std;
    double total, choices;
    cout << "Enter the total number of choices on the game card and\n"
            "the number of picks allowed:\n";
    while ((cin >> total >> choices) && choices <= total)
    {
        cout << "You have one chance in ";
        cout << probability(total, choices);      // compute the odds
        cout << " of winning.\n";
        cout << "Next two numbers (q to quit): ";
    }
    cout << "bye\n";
    // cin.get();
    // cin.get();
    return 0;
}

// the following function calculates the probability of picking picks
// numbers correctly from numbers choices
long double probability(unsigned numbers, unsigned picks)
{
    long double result = 1.0;  // here come some local variables
    long double n;
    unsigned p;

    for (n = numbers, p = picks; p > 0; n--, p--)
        result = result * n / p ; 
    return result;
}

修改后:

[code]#include <iostream>
long double probability(unsigned numbers, unsigned picks, unsigned extra);
int main()
{
    using namespace std;
    double total, choices, extra;
    cout << "Enter the total number of choices on the game card ,\n"
            "the number of picks allowed and the extra number:\n";
    while ((cin >> total >> choices >> extra) && choices <= total && 1<=extra<=27)
    {
        cout << "You have one chance in ";
        cout << probability(total, choices, extra);      // compute the odds
        cout << " of winning.\n";
        cout << "Next two numbers (q to quit): ";
    }
    cout << "bye\n";

    return 0;
}
long double probability(unsigned numbers, unsigned picks, unsigned extra)
{
    long double result = 1.0;  // here come some local variables
    long double n;
    unsigned p;

    for (n = numbers, p = picks; p > 0; n--, p--)
        result = result * n / p ;
    result = result * extra;
    return result;
}

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

[code]#include <iostream>

double calculate(int);

int main()
{
    using namespace std;
    
    double factorial;
    int a;

    cout << "请输入数字:";
    while (cin>>a)
        cout << a << "的阶乘为:" << calculate(a) << endl;
    cout << "end";    
    
    return 0;
}

double calculate(int a)
{
    if (0 == a)
        return 1;
    if (1 == a)
        return 1;
    else
        return a * calculate(a-1);
}

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

[code]#include <iostream>

int Fill_array(double arr[], int size);
void Show_array(double arr[], int size);
void Reverse_array(double arr[], int size);

int main()
{
    using namespace std;
    const int size = 10;
    double arr[size];
    int real_size;
    
    real_size = Fill_array(arr, size);
    Show_array(arr, real_size);
    
    Reverse_array(arr, real_size);
    cout << "\n顺序反转后,如下:\n";
    Show_array(arr, real_size);
    
    Reverse_array(arr+1, real_size-2);
    cout << "\n再次反转除第一个和最后一个元素之外的所有元素后,如下:\n";
    Show_array(arr, real_size);
    
    return 0;
}

int Fill_array(double arr[], int size)
{
    using namespace std;
    double a;
    int i = 0;
    
    cout << "请输入最多10个数字:\n";
    while (cin >> a)
    {
        arr[i] = a;
        i++;
        if (i==size)
            break;
    }
    cout << "一共显示了" << i << "个数字:\n";
    return i;
}
    
void Show_array(double arr[], int size)
{
    using namespace std;
    for (int i = 0; i<size; i++)
        cout << "第" << i+1 << "个数字为:\t" << arr[i] << endl;
}

void Reverse_array(double arr[], int size)
{
    double change;
    int i, j;
    for (i = 0, j = size-1; i < j; i++, j--)
    {
        change = arr[i];
        arr[i] = arr[j];
        arr[j] = change;
    }
}    

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

[code]// arrfun3.cpp -- array functions and const
#include <iostream>
const int Max = 5;

// function prototypes
int fill_array(double ar[], int limit);
void show_array(const double ar[], int n);  // don't change data
void revalue(double r, double ar[], int n);

int main()
{
    using namespace std;
    double properties[Max];

    int size = fill_array(properties, Max);
    show_array(properties, size);
    if (size > 0)
    {
        cout << "Enter revaluation factor: ";
        double factor;
        while (!(cin >> factor))    // bad input
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
           cout << "Bad input; Please enter a number: ";
        }
        revalue(factor, properties, size);
        show_array(properties, size);
    }
    cout << "Done.\n";
    // cin.get();
    // cin.get();
    return 0;
}

int fill_array(double ar[], int limit)
{
    using namespace std;
    double temp;
    int i;
    for (i = 0; i < limit; i++)
    {
        cout << "Enter value #" << (i + 1) << ": ";
        cin >> temp;
        if (!cin)    // bad input
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
           cout << "Bad input; input process terminated.\n";
           break;
        }
        else if (temp < 0)     // signal to terminate
            break;
        ar[i] = temp;
    }
    return i;
}

// the following function can use, but not alter,
// the array whose address is ar
void show_array(const double ar[], int n)
{
    using namespace std;
    for (int i = 0; i < n; i++)
    {
        cout << "Property #" << (i + 1) << ": $";
        cout << ar[i] << endl;
    }
}

// multiplies each element of ar[] by r
void revalue(double r, double ar[], int n)
{
    for (int i = 0; i < n; i++)
        ar[i] *= r;
}

修改后:

[code]#include <iostream>
const int Max = 5;

double* fill_array(double ar[], int limit);
void show_array(const double ar[], double* lastpoint);
void revalue(double r, double ar[], double* lastpoint);

int main()
{
    using namespace std;
    double properties[Max];

    double* lastpoint = fill_array(properties, Max);
    show_array(properties, lastpoint);
    if (lastpoint > properties)
    {
        cout << "Enter revaluation factor: ";
        double factor;
        while (!(cin >> factor))
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
           cout << "Bad input; Please enter a number: ";
        }
        revalue(factor, properties, lastpoint);
        show_array(properties, lastpoint);
    }
    cout << "Done.\n";

    return 0;
}

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

void show_array(const double ar[], double* lastpoint)
{
    using namespace std;
    for (int i = 0; i < lastpoint-ar; i++)
    {
        cout << "Property #" << (i + 1) << ": $";
        cout << ar[i] << endl;
    }
}

void revalue(double r, double ar[], double* lastpoint)
{
    for (int i = 0; i < lastpoint-ar; i++)
        ar[i] *= r;
}

或者

[code]#include <iostream>
const int Max = 5;

double* fill_array(double ar[], int limit);
void show_array(const double ar[], double* lastpoint);
void revalue(double r, double ar[], double* lastpoint);

int main()
{
    using namespace std;
    double properties[Max];

    double* lastpoint = fill_array(properties, Max);
    show_array(properties, lastpoint);
    if (lastpoint != properties)
    {
        cout << "Enter revaluation factor: ";
        double factor;
        while (!(cin >> factor))
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
           cout << "Bad input; Please enter a number: ";
        }
        revalue(factor, properties, lastpoint);
        show_array(properties, lastpoint);
    }
    cout << "Done.\n";

    return 0;
}

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

void show_array(const double ar[], double* lastpoint)
{
    using namespace std;
    for (const double* i = ar; i != lastpoint; i++)
    {
        cout << "Property #" << (i-ar + 1) << ": $";
        cout << *i << endl;
    }
}

void revalue(double r, double ar[], double* lastpoint)
{
    for (double* i = ar; i != lastpoint; i++)
        *i *= r;
}

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

[code]//arrobj.cpp -- functions with array objects
#include <iostream>
#include <array>
#include <string>
const int Seasons = 4;
const std::array<std::string, Seasons> Snames =
    {"Spring", "Summer", "Fall", "Winter"};

void fill(std::array<double, Seasons> * pa);
void show(std::array<double, Seasons> da);
int main()
{
    std::array<double, 4> expenses;
    fill(&expenses);
    show(expenses);
    // std::cin.get();
    // std::cin.get();
    return 0;
}

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

void show(std::array<double, Seasons> da)
{
    double total = 0.0;
    std::cout << "\nEXPENSES\n";
    for (int i = 0; i < Seasons; i++)
    {
        std::cout << Snames[i] << ": $" << da[i] << '\n';
        total += da[i];
    }
    std::cout << "Total: $" << total << '\n';
}

使用a方法修改后:

[code]#include <iostream>

const int Seasons = 4;
const char Snames[4][7] = {"Spring", "Summer", "Fall", "Winter"};

void fill(double pa[]);
void show(double da[]);
int main()
{
    double expenses[4];
    fill(expenses);
    show(expenses);

    return 0;
}

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

void show(double da[])
{
    double total = 0.0;
    std::cout << "\nEXPENSES\n";
    for (int i = 0; i < Seasons; i++)
    {
        std::cout << Snames[i] << ": $" << da[i] << '\n';
        total += da[i];
    }
    std::cout << "Total: $" << total << '\n';
}

使用b方法修改后:

[code]#include <iostream>

const int Seasons = 4;
const char Snames[4][7] = {"Spring", "Summer", "Fall", "Winter"};

struct struct_expenses
{
    double expenses[4];
};

void fill(struct_expenses*);
void show(struct_expenses*);

int main()
{
    struct_expenses object_expenses;
    fill(&object_expenses);
    show(&object_expenses);

    return 0;
}

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

void show(struct_expenses* object_expenses_point)
{
    double total = 0.0;
    std::cout << "\nEXPENSES\n";
    for (int i = 0; i < Seasons; i++)
    {
        std::cout << Snames[i] << ": $" << object_expenses_point->expenses[i] << '\n';
        total += object_expenses_point->expenses[i];
    }
    std::cout << "Total: $" << total << '\n';
}

或者使用b方法,按值传入结构

[code]#include <iostream>

const int Seasons = 4;
const char Snames[4][7] = {"Spring", "Summer", "Fall", "Winter"};

struct struct_expenses
{
    double expenses[4];
};

struct_expenses fill();
void show(struct_expenses);

int main()
{
    struct_expenses object_expenses;
    object_expenses = fill();
    show(object_expenses);

    return 0;
}

struct_expenses fill()
{
    struct_expenses object_expenses;
    for (int i = 0; i < Seasons; i++)
    {
        std::cout << "Enter " << Snames[i] << " expenses: ";
        std::cin >> object_expenses.expenses[i];
    }
    return object_expenses;
}

void show(struct_expenses object_expenses)
{
    double total = 0.0;
    std::cout << "\nEXPENSES\n";
    for (int i = 0; i < Seasons; i++)
    {
        std::cout << Snames[i] << ": $" << object_expenses.expenses[i] << '\n';
        total += object_expenses.expenses[i];
    }
    std::cout << "Total: $" << total << '\n';
}

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

[code]#include <iostream>
using namespace std;

const int SLEN = 30;

struct student {
    char fullname[SLEN];
    char hobby[SLEN];
    int ooplevel;
};

// getinfo() has two arguements:a pointer to the first element of an array of student structures 
// and an int representing the number of element of the array.
// getinfo()有两个参数:指向student结构数组的第一个元素的指针和一个表示数组元素个数的int。  
// The function solicits and stores data about students. 
// 该函数征求并存储有关学生的数据。
// It terminates input upon filling the array pr upon encountering a blank line for the student name. 
// 它在遇到学生姓名的空行时填写数组pr时终止输入。
// The function returns the actual number of array element filled.
// 该函数返回填充的数组元素的实际数量。

int getinfo(student pa[], int n);

// display1() takes a student structures as an argument and displays its contents
// display1() 将student结构作为参数并显示其内容 

void diaplay1(students st);

// display2() take the address of student structure as an arguement and displays the structure's contents
// display 2() 以学生结构的地址为参数,显示结构的内容
void display2(const students * ps);

// display3() takes the address of the first element of an array of student structures and 
// the number of number of array element as arguements and displays the contents of the structures
// display3()将student结构数组的第一个元素的地址和数组元素的数量作为参数,并显示结构的内容
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();
        display2();
    }
    display3(ptr_stu, entered);
    delete [] ptr_stu;
    cout << "Done\n";
    return 0;
}


完成后:

[code]#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 real_num = 0;
    for (int i=0; i < n; i++)
    {
        cout << "请输入第" << i+1 << "个学生的信息:\n";
        cout << "姓名:";
        cin.get(pa[i].fullname, SLEN).get();
        cout << "爱好:";
        cin.get(pa[i].hobby, SLEN).get();
        cout << "ooplevel:";
        cin >> pa[i].ooplevel;
        cin.get();
        
        real_num++;
    }
    return real_num;
}

void display1(student st)
{
    cout << "display1 学生姓名:" << st.fullname << endl;
    cout << "display1 爱好:" << st.hobby << endl;
    cout << "display1 ooplevel:" << st.ooplevel << endl;
}
    
void display2(const student * ps)
{
    cout << "display2 学生姓名:" << ps->fullname << endl;
    cout << "display2 爱好:" << ps->hobby << endl;
    cout << "display2 ooplevel:" << ps->ooplevel << endl;
}

void display3(const student pa[], int n)
{
    for (const student* stu_point = pa; stu_point != pa+n; stu_point++)
    {
        cout << "display3 学生姓名:" << stu_point->fullname << endl;
        cout << "display3 爱好:" << stu_point->hobby << endl;
        cout << "display3 ooplevel:" << stu_point->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);    其中包含三个指针
    可以采用数组初始化语法,并将函数名作为地址来初始化这样的数组。

10.1 版本1,使用switch分别调用

[code]#include <iostream>

double add(double x, double y);
double multiply(double x, double y);
double subtract(double x, double y);
double calculate(double a, double b, double (*pf)(double, double));

int main()
{
    using namespace std;
    char choose;
    double a, b;
    
    cout << "请输入由空白隔开的两个数字:\n";
    while(cin >> a >> b)
    {
        cin.get();
        cout << "请选择您想要进行的运算(输入+ 或 * 或 -):";
        cin.get(choose);
        switch (choose)
        {
            case '+' : cout << a << "+" << b << "=" << calculate(a, b, add) << endl;
                       break;
            case '-' : cout << a << "-" << b << "=" << calculate(a, b, subtract) << endl;
                       break;
            case '*' : cout << a << "*" << b << "=" << calculate(a, b, multiply) << endl;
                       break;
            default : cout << "choose error\n";
        }
        cout << "\n请输入由空白隔开的两个数字:\n";
    }
    cout << "end";

    return 0;
}

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 calculate(double a, double b, double (*pf)(double, double))
{
    return (*pf)(a, b);       //或者return pf(a, b);
}

10.2 版本2,使用函数指针数组循环调用

[code]#include <iostream>

double add(double x, double y);
double multiply(double x, double y);
double subtract(double x, double y);
double calculate(double a, double b, double (*pf)(double, double));

int main()
{
    using namespace std;
    char choose;
    double a, b;
    double (*pf[3])(double, double) = {add, subtract, multiply};
    char symbol[3] = {'+', '-', '*'};
    
    cout << "请输入由空白隔开的两个数字:\n";
    while(cin >> a >> b)
    {
        cin.get();
        for(int i = 0; i < 3; i++)
            cout << a << symbol[i] << b << "=" << calculate(a, b, pf[i]) << endl;
   
        cout << "\n请输入由空白隔开的两个数字:\n";
    }
    cout << "end";

    return 0;
}

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 calculate(double a, double b, double (*pf)(double, double))
{
    return (*pf)(a, b);       //或者return pf(a, b);
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: