C++ Primer Plus 第六版(中文版)第七、八章(完美修订版)编程练习答案

//本博主所写的代码仅为阅读者提供参考;

//若有不足之处请提出,博主会尽所能修改;

//附上课后编程练习题目;

//若是对您有用的话请点赞或分享提供给它人;


//7.13 - 1.cpp

#include <iostream>
using namespace std;

double harmonic_mean(double x, double y);

int main()
{
    
    
    double a, b;

    cout << "Please enter two numbers (0 to quit): ";
    while (cin >> a >> b && a != 0 && b != 0)
    {
    
    
        cout << "The harmonic mean of " << a;
        cout << " and " << b << " is ";
        cout << harmonic_mean(a, b) << endl;
        cout << "Next two numbers (0 to quit): ";
    }
    cout << "Bye." << endl;

    return 0;
}

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

//-------------

//7.13 - 2.cpp

#include <iostream>
using namespace std;

int initialize_array(double arr[], int n);
void show_array(const double arr[], int n);
void count_average(const double arr[], int n);

const int ArSize = 10;

int main()
{
    
    
    int n;
    double golf[ArSize];

    n = initialize_array(golf, ArSize);
    show_array(golf, n);
    count_average(golf, n);
    cout << "Bye." << endl;

    return 0;
}

int initialize_array(double arr[], int n)
{
    
    
    int i = 0;

    cout << "You can enter up to " << ArSize;
    cout << " golf scores (q to terminate)." << endl;

    cout << "Golf scores #1: ";
    while (i < n && cin >> arr[i])
    {
    
    
        if (++i < ArSize)
        {
    
    
            cout << "Golf scores #" << i + 1 << ": ";
        }
    }
    return i;
}

void show_array(const double arr[], int n)
{
    
    
    cout << "All golf scores:" << endl;
    for (int i = 0; i < n; i++)
    {
    
    
        cout << arr[i] << ' ';
    }
    cout.put('\n');
    return;
}

void count_average(const double arr[], int n)
{
    
    
    double aver = 0.0;

    for (int i = 0; i < n; i++)
    {
    
    
        aver += arr[i];
    }
    aver /= n;
    cout << "Average golf scores: " << aver << endl;
    return;
}

//-------------

//7.13 - 3.cpp

#include <iostream>
using namespace std;

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

void value_show_box(box temp);
void address_show_box(box *temp);

int main()
{
    
    
    box smallbox = {
    
    "Cute box", 20, 10, 30, 50};

    value_show_box(smallbox);
    address_show_box(&smallbox);
    value_show_box(smallbox);

    return 0;
}

void value_show_box(box temp)
{
    
    
    cout << "\nBox informations: " << endl;
    cout << "Name: " << temp.maker << endl;
    cout << "height: " << temp.height << endl;
    cout << "width: " << temp.width << endl;
    cout << "length: " << temp.length << endl;
    cout << "volume: " << temp.volume << endl;
    return;
}

void address_show_box(box *temp)
{
    
    
    temp->volume = temp->height * temp->width * temp->length;
    return;
}

//-------------

//7.13 - 4.cpp

#include <iostream>
using namespace std;

long double probability(unsigned numbers, unsigned picks);

int main()
{
    
    
    unsigned total, choices, temp;
    cout << "Enter the total number of choices on the game card and\n";
    cout << "the number of picks allowed and the second section(<= total number):" << endl;
    while ((cin >> total >> choices >> temp) && choices <= total && temp <= total)
    {
    
    
        cout << "You have one chance in ";
        cout << probability(total, choices) * probability(temp, 1); //2个选择的乘积;
        cout << " of winning.\n";
        cout << "Next three numbers (q to quit): ";
    }
    cout << "bye!\n";

    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 *= n / p;
    }
    return 1.0 / result; //源程序7.4中奖概率不对,应该是result计算完之后的倒数,在此进行改正;
}

//-------------

//7.13 - 5.cpp

#include <iostream>
using namespace std;

long double factorial(long double n);

int main()
{
    
    
    long double temp;

    cout << "Please enter a number(<0 or q to quit): ";
    while (cin >> temp && temp >= 0)
    {
    
    
        cout << temp << "! = " << factorial(temp) << endl;
        cout << "Next number(<0 or q to quit): ";
    }
    cout << "Bye." << endl;

    return 0;
}

long double factorial(long double n)
{
    
    
    if (0 == n)
    {
    
    
        return 1;
    }
    else
    {
    
    
        return n * factorial(n - 1);
    }
}

//-------------

//7.13 - 6.cpp

#include <iostream>
using namespace std;

int Fill_array(double arr[], int n);
void Show_array(const double arr[], int n);
void Reverse_average(double arr[], int n);

const int ArSize = 10;

int main()
{
    
    
    int n;
    double arr[ArSize];

    n = Fill_array(arr, ArSize);
    Show_array(arr, n);
    Reverse_average(arr, n);
    Show_array(arr, n);
    Reverse_average(arr + 1, n - 2);
    Show_array(arr, n);
    cout << "Bye." << endl;

    return 0;
}

int Fill_array(double arr[], int n)
{
    
    
    int i = 0;

    cout << "You can enter up to " << ArSize;
    cout << " numbers (q to terminate)." << endl;

    cout << "Number #1: ";
    while (i < n && cin >> arr[i])
    {
    
    
        if (++i < ArSize)
        {
    
    
            cout << "Number #" << i + 1 << ": ";
        }
    }
    return i;
}

void Show_array(const double arr[], int n)
{
    
    
    cout << "All numbers:" << endl;
    for (int i = 0; i < n; i++)
    {
    
    
        cout << arr[i] << ' ';
    }
    cout.put('\n');
    return;
}

void Reverse_average(double arr[], int n)
{
    
    
    double temp;

    for (int i = 0; i < n / 2; i++)
    {
    
    
        temp = arr[n - 1 - i];
        arr[n - 1 - i] = arr[i];
        arr[i] = temp;
    }
    return;
}

//-------------

//7.13 - 7.cpp

#include <iostream>
using namespace std;

const int Max = 5;

double *fill_array(double *begin, double *end);
void show_array(const double *begin, double *end);
void revalue(double r, double *begin, double *end);

int main()
{
    
    
    double properties[Max];

    double *size = fill_array(properties, properties + Max);
    show_array(properties, size);
    if (size - properties > 0)
    {
    
    
        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, size);
        show_array(properties, size);
    }
    cout << "Done.\n";

    return 0;
}

double *fill_array(double *begin, double *end)
{
    
    
    int i;
    double temp;
    double *ptr;

    for (i = 0, ptr = begin; ptr < end; i++, ptr++)
    {
    
    
        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;
        }
        *ptr = temp;
    }
    return begin + i;
}

void show_array(const double *begin, double *end)
{
    
    
    int i;
    const double *ptr;

    for (i = 0, ptr = begin; ptr < end; i++, ptr++)
    {
    
    
        cout << "Property #" << (i + 1) << ": $";
        cout << *ptr << endl;
    }
    return;
}

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

//-------------

//7.13 - 8(a).cpp

#include <iostream>

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

void fill(double pa[], int n);
void show(const double pa[], int n);

int main()
{
    
    
    double expenses[Seasons];
    fill(expenses, Seasons);
    show(expenses, Seasons);

    return 0;
}

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

void show(const double pa[], int n)
{
    
    
    double total = 0.0;

    std::cout << "\nEXPENSES\n";
    for (int i = 0; i < n; i++)
    {
    
    
        std::cout << Snames[i] << ": $" << pa[i] << '\n';
        total += pa[i];
    }
    std::cout << "Total: $" << total << '\n';
    return;
}

//-------------

//7.13 - 8(b).cpp

#include <iostream>

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

struct spending
{
    
    
    double expenses[Seasons];
};

void fill(spending *temp);
void show(spending *temp);

int main()
{
    
    
    spending temp;
    fill(&temp);
    show(&temp);

    return 0;
}

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

void show(spending *temp)
{
    
    
    double total = 0.0;

    std::cout << "\nEXPENSES\n";
    for (int i = 0; i < Seasons; i++)
    {
    
    
        std::cout << Snames[i] << ": $" << temp->expenses[i] << '\n';
        total += temp->expenses[i];
    }
    std::cout << "Total: $" << total << '\n';
    return;
}

//-------------

//7.13 - 9.cpp

#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)
{
    
    
    cout << "You can enter up to " << n;
    cout << " students' messages (enter to terminate)." << endl;

    for (int i = 0; i < n; i++)
    {
    
    
        cout << "Student #" << i + 1 << ": " << endl;
        cout << "Enter the fullname(a blank line to quit): ";
        cin.getline(pa[i].fullname, SLEN);
        if ('\0' == pa[i].fullname[0]) //题目要求空行结束输入;
        {
    
    
            break;
        }
        cout << "Enter the hobby: ";
        cin.getline(pa[i].hobby, SLEN);
        cout << "Enter the ooplevel: ";
        while (!(cin >> pa[i].ooplevel))
        {
    
    
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Please enter an number: ";
        }
        cin.get(); //吸收正确输入时的换行符;
    }
    return i;
}

void display1(student st)
{
    
    
    cout << "\nName: " << st.fullname << endl;
    cout << "Hobby: " << st.hobby << endl;
    cout << "Ooplevel: " << st.ooplevel << endl;
    return;
}

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

void display3(const student pa[], int n)
{
    
    
    if (n > 0)
    {
    
    
        cout << "\nAll students' information:" << endl;
        for (int i = 0; i < n; i++)
        {
    
    
            cout << "Name: " << pa[i].fullname << endl;
            cout << "Hobby: " << pa[i].hobby << endl;
            cout << "Ooplevel: " << pa[i].ooplevel << endl;
        }
    }
    return;
}

//-------------

//7.13 - 10.cpp

#include <iostream>
using namespace std;

double calculate(double a, double b, double (*p)(double a, double b));
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);

int main()
{
    
    
    double a, b;
    double (*pf[3])(double a, double b) = {
    
    add, subtract, multiply};

    cout << "Enter two numbers (q to quit): ";
    while (cin >> a >> b)
    {
    
    
        for (int i = 0; i < 3; i++)
        {
    
    
            switch (i)
            {
    
    
            case 0:
            {
    
    
                cout << "The " << a << " + " << b << " answer is: " << (*pf[i])(a, b) << endl;
                break;
            }
            case 1:
            {
    
    
                cout << "The " << a << " - " << b << " answer is: " << (*pf[i])(a, b) << endl;
                break;
            }
            case 2:
            {
    
    
                cout << "The " << a << " * " << b << " answer is: " << (*pf[i])(a, b) << endl;
                break;
            }
            }
        }
        cout << "Next two numbers (q to quit): ";
    }
    cout << "Done!" << endl;

    return 0;
}

double calculate(double a, double b, double (*p)(double a, double b))
{
    
    
    return (*p)(a, b);
}

double add(double a, double b)
{
    
    
    return a + b;
}

double subtract(double a, double b)
{
    
    
    return a - b;
}

double multiply(double a, double b)
{
    
    
    return a * b;
}

//-------------

//8.8 - 1.cpp

#include <iostream>
using namespace std;

void print_string(const char *str, int i = 0);

int main()
{
    
    
    const char *str = "This is a test.";

    cout << "Only one parameter, print 1 times:" << endl;
    print_string(str);
    cout << "Having two parameter can print arbitrary times:" << endl;
    print_string(str, 3);
    cout << "Bye." << endl;

    return 0;
}

void print_string(const char *str, int i)
{
    
    
    cout << str << endl;
    if (i > 1)
    {
    
    
        print_string(str, i - 1); //递归进行输出i次str字符串;
    }
    return;
}

//-------------

//8.8 - 2.cpp

#include <iostream>
#include <cstring>

struct CandyBar
{
    
    
    char brand[20];
    double weight;
    int calorie;
};

void initialize_candybar(CandyBar &temp, const char *str = "Millennium Munch", double w = 2.85, int c = 350);
void show_candybar(const CandyBar &temp);

int main()
{
    
    
    CandyBar mycandybar;

    initialize_candybar(mycandybar);
    show_candybar(mycandybar);

    return 0;
}

void initialize_candybar(CandyBar &temp, const char *str, double w, int c)
{
    
    
    strcpy(temp.brand, str);
    temp.weight = w;
    temp.calorie = c;
    return;
}

void show_candybar(const CandyBar &temp)
{
    
    
    using namespace std;
    cout << "Output CandyBar information:" << endl;
    cout << "Brand: " << temp.brand << endl;
    cout << "Weight: " << temp.weight << endl;
    cout << "Calorie: " << temp.calorie << endl;
    return;
}

//-------------

//8.8 - 3.cpp

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

void print_upper_string(string &str);

int main()
{
    
    
    string str;

    cout << "Enter a string (q to quit): ";
    while (getline(cin, str) && str != "q")
    {
    
    
        print_upper_string(str);
        cout << str << endl;
        cout << "Next string (q to quit): ";
    }
    cout << "Bye." << endl;

    return 0;
}

void print_upper_string(string &str)
{
    
    
    for (int i = 0; i < str.size(); i++)
    {
    
    
        str[i] = toupper(str[i]);
    }
    return;
}

//-------------

//8.8 - 4.cpp

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

struct stringy
{
    
    
    char *str;
    int ct;
};

void set(stringy &stry, const char *str);
void show(stringy &stry, int i = 1);
void show(const char *str, int i = 1);

int main()
{
    
    
    stringy beany;
    char testing[] = "Reality isn't what it used to be.";

    set(beany, testing);
    show(beany);
    show(beany, 2);
    testing[0] = 'D';
    testing[1] = 'u';
    show(testing);
    show(testing, 3);
    delete[] beany.str; //题目中未释放new分配的内存,在此添加释放内存语句;
    show("Done!");

    return 0;
}

void set(stringy &stry, const char *str)
{
    
    
    stry.str = new char[strlen(str) + 1];
    strcpy(stry.str, str);
    return;
}

void show(stringy &stry, int i)
{
    
    
    cout << stry.str << endl;
    if (i > 1)
    {
    
    
        for (int k = 0; k < i - 1; k++)
        {
    
    
            cout << stry.str << endl;
        }
    }
    return;
}

void show(const char *str, int i)
{
    
    
    cout << str << endl;
    if (i > 1)
    {
    
    
        for (int k = 0; k < i - 1; k++)
        {
    
    
            cout << str << endl;
        }
    }
    return;
}

//-------------

//8.8 - 5.cpp

#include <iostream>
using namespace std;

template <typename T>
T max5(const T *array);

int main()
{
    
    
    int test1[5] = {
    
    1, 3, 5, 7, 9};
    double test2[5] = {
    
    10.0, 20.0, 15.0, 12.0, 30.0};

    cout << "The max of int array is: " << max5(test1) << endl;
    cout << "The max of double array is: " << max5(test2) << endl;

    return 0;
}

template <typename T>
T max5(const T *array)
{
    
    
    T temp = array[0];

    for (int i = 1; i < 5; i++)
    {
    
    
        if (temp < array[i])
        {
    
    
            temp = array[i];
        }
    }
    return temp;
}

//-------------

//8.8 - 6.cpp

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

template <typename T>
T maxn(T *arr, int n);

template <>
const char *maxn(const char *str[], int n);

int main()
{
    
    
    int test1[6] = {
    
    1, 3, 5, 7, 9, 11};
    double test2[4] = {
    
    10.0, 20.0, 15.0, 12.0};
    const char *test3[5] = {
    
    "123", "12345", "123456", "abcdefg", "xio"};

    cout << "The max of int array is: " << maxn(test1, 6) << endl;
    cout << "The max of double array is: " << maxn(test2, 4) << endl;
    cout << "The max of string array is: " << maxn(test3, 5) << endl;

    return 0;
}

template <typename T>
T maxn(T *arr, int n)
{
    
    
    T temp = arr[0];

    for (int i = 0; i < n; i++)
    {
    
    
        if (temp < arr[i])
        {
    
    
            temp = arr[i];
        }
    }
    return temp;
}

template <>
const char *maxn(const char *str[], int n)
{
    
    
    const char *temp = *str;

    for (int i = 1; i < n; i++)
    {
    
    
        if (strlen(temp) < strlen(str[i]))
        {
    
    
            temp = str[i];
        }
    }
    return temp;
}

//-------------

//8.8 - 7.cpp

#include <iostream>

template <typename T>
T SumArray(T arr[], int n);

template <typename T>
T SumArray(T *arr[], int n);

struct debts
{
    
    
    char name[50];
    double amount;
};

int main()
{
    
    
    using namespace std;
    int things[6] = {
    
    13, 31, 103, 301, 310, 130};
    debts mr_E[3] =
    {
    
    
        {
    
    "Ima Wolfe", 2400.0},
        {
    
    "Ura Foxe", 1300.0},
        {
    
    "Iby Stout", 1800.0}
    };

    double *pd[3];
    for (int i = 0; i < 3; i++)
    {
    
    
        pd[i] = &mr_E[i].amount;
    }

    cout << "Listing Mr. E's total of things:" << endl;
    cout << SumArray(things, 6) << endl;
    cout << "Listing Mr. E's total of debts:" << endl;
    cout << SumArray(pd, 3) << endl;

    return 0;
}

template <typename T>
T SumArray(T arr[], int n)
{
    
    
    using namespace std;
    double sum = 0.0;
    for (int i = 0; i < n; i++)
    {
    
    
        sum += arr[i];
    }
    return sum;
}

template <typename T>
T SumArray(T *arr[], int n)
{
    
    
    using namespace std;
    double sum = 0.0;
    for (int i = 0; i < n; i++)
    {
    
    
        sum += *arr[i];
    }
    return sum;
}

//-------------

//------------------------------------------2020年9月27日 ----------------------------------------------;

猜你喜欢

转载自blog.csdn.net/m0_46181359/article/details/108825885