C++ primer plus 第六版 第七章 编程练习答案

第七章 编程练习答案

这是第一次把课后编程写出来记录,答案基本都是自己的想法加参考书中的例子,不过部分类型的写法和输入输出不懂,参考了别人的的代码。以后要及时记录代码,并且注释明白,感觉这样会加深理解。希望以后看到能够轻松搞明白。

1.

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

int main() 
{
    double x, y, z;
    cout << "Enter two numbers (0 to quit): " << endl;
    cin >> x;
    cin >> y;
    while ( x != 0 && y != 0)
    {
        z = tiaohe(x, y);
        cout << z << endl;
        cout << "Enter two numbers (0 to quit): " << endl;
        cin >> x >> y;
    } 
    cout << "Done." << endl;

    return 0;
}

double tiaohe (double x, double y)
{
    double ans;
    ans = 2.0 * x * y / ( x + y);
    return ans;
}

2.

#include <iostream>

using namespace std;

const int Max = 10;

void show(double arr[], int n);
double sum(double arr[], int n);

int main ()
{

    double average;
    double arr[Max];

    cout << "Please enter golf scores.\n";
    cout << "You may enter up to " << Max
         << " golf scores.\n";
    cout << "score #1: ";
//get data  
    int i = 0;
    int n = 0;
    while (i < Max && cin >> arr[i])
    {
        if (++i < Max)
            cout << "score #" << i+1 << ": ";
        n++;
    };
    cout << "\nThe result of golf scores: " << endl;
//calculate average, report result  
    show(arr, n);
    average = sum(arr, n) /n;
    cout << "\nThe average of golf scores: " << average << "\n";

    return 0;   
}

void show(double arr[], int n)
{
    int total = 0;
    for(int i = 0; i < n; i++)
    {
        cout << "score #" << i+1 << ": ";
        cout << arr[i] << endl; 
    }
}

double sum(double arr[], int n)
{
    double total = 0;
    for(int i = 0; i < n; i++)
        total = total + arr[i];
    return total;
}

3.

#include <iostream>

using namespace std;

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

void show(box Alex);//按值传递结构 
void show_volume(box * p_box);// 传递结构的地址 

int main ()
{
    box Alex;

    cout << "Enter the maker: " << endl;
    cin.get( Alex.maker, 40);
    cin.get();//注意字符输入 
    cout << "Enter the height: " << endl;
    cin >> Alex.height;
    cout << "Enter the width: " << endl;
    cin >> Alex.width;
    cout << "Enter the length: " << endl;
    cin >> Alex.length;         

    show_volume(&Alex);
    show(Alex);

    return 0;
}
//函数a 
void show(box Alex)
{
    cout << "\nThe maker is: ";
    cout << Alex.maker << endl;
    cout << "The height is: ";
    cout << Alex.height << endl;
    cout << "The width is: ";   
    cout << Alex.width << endl;
    cout << "The length is: ";
    cout << Alex.length << endl;
    cout << "The volume is: ";
    cout << Alex.volume << endl;        
}
//函数b 
void show_volume(box * p_box)
{
    p_box->volume = p_box->height * p_box->width * p_box->length;
}

4.

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

int main()
{
    double total, choices, s;
    cout << "Enter the find number of choices on the game card, the number\n"
            "of picks allowedand and the special number:\n";
    while((cin >> total >> choices >> s) && choices <= total)//输入条件 
    {
        cout << "You have one chance in ";
        cout << probability(total, choices, s);
        cout << " of winning.\n";
        cout << "Next two numbers (q to quit): ";
    }
    cout << "bye!\n";
    return 0;
}

long double probability(unsigned numbers, unsigned picks, int s)
{
    long double result = 1.0;
    long double n;
    unsigned p;

    for (n = numbers, p = picks; p > 0; n--, p--)
        result = result * n / p ;//减小中间变量 
    result = result * s; 
    return result;
}

5.

#include<iostream>

using namespace std;

long int factorial(int n);//函数声明

int main()
{
    int x;
    long int ans;
    cout << "Please enter the number: (q to quit)" << endl;

    while(cin >> x)//控制输入条件,非数字时结束 
    {

    cout << "The factorial is: "<< factorial(x) << endl;                

    }
    cout << "Over." << endl;

    return 0;
}
//递归思想 
long int factorial(int n)
{
    long int ans;
    if (n >0)
        ans = n * factorial(n-1);
    if (n == 0)
        ans = 1;
    return ans;
}

6.

#include <iostream>

using namespace std;
//函数声明 
int Fill_array(double arr[], int n);
void Show_array(double arr[], int n);
void Reverse_array(double arr[], int bagin, int end, int n);

int main()
{
    int n, size;

    cout << "Please enter the number of array: " << endl;

    cin >> size;

    double arr[size];

    n = Fill_array(arr, size);

    Show_array(arr, n);

    Reverse_array(arr, 0, n-1, n);

    Show_array(arr, n); 

    Reverse_array(arr, 1, n-2, n);//除首尾元素外进行交换 

    Show_array(arr, n); 

    cout << "Over.\n";

    return 0;
}

//填充函数 
int Fill_array(double arr[], int n)
{
    int count = 0;
    cout << "Please enter the array: " << endl; 
    for(int i = 0; i < n && cin >> arr[i]; i++)//注意输入条件 
    {
        count++;        
    }   

    return count;
}

//显示函数 
void Show_array(double arr[], int n)
{
    cout << "Now, the array is: " << endl;
    for(int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";      
    }
    cout << endl;
}

//反转函数 
void Reverse_array(double arr[], int begin, int end, int n)//注意参数起止 
{
    int t;
    for(int i = begin; i < n/2; i++)
    {
        t = arr[i];     
        arr[i] = arr[begin + end - i];//注意参数起止对交换的影响    
        arr[begin + end - i] = t;       
    }   
}

7.

#include <iostream>

using namespace std;

const int Max = 5;
double * fill_array(double * p_begin, double * p_end);//如何用两个指针表示区间 
void show_array(double * p_begin, double * p_end);//注意这里的类型要前后一致 
void revalue(double r, double * p_begin, double * p_end);

int main()
{

    double properties[Max];

    double * pt = fill_array(properties, properties + Max);

    show_array(properties, pt);

    if (properties != pt)//当首尾地址不同,即存在区间时 
    {
        cout << "Enter revaluation factor: ";
        double factor;
        while(!(cin >> factor))//输入错误时返回false值,取反执行该操作 
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Bad input: Please enter a number: ";
        }
        revalue(factor, properties, pt);
        show_array(properties, pt);
    }
    cout << "Done.\n";
    return 0;

}

//填充数组 
double * fill_array(double * p_begin, double * p_end)
{
    int i = 1;
    double * pt;
    for (pt = p_begin; pt != p_end; pt++, i++)
    {
        cout << "Enter value #" << i << ": ";
        cin >> *pt;
//-----------输入非数字和负数的情况------------------------ 
        if (!cin)
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Bad input; input process terminated.\n";
            break;
        }
        else if (*pt < 0)
            break;
    }
//-----------传递指针,注意这里传递的是地址,要用&----------  
    return &(*pt);
}


//显示数组 
void show_array(double * p_begin, double * p_end)
{
    int i = 1;
    double * pt;
    for (pt = p_begin; pt != p_end; pt++, i++)//注意这里用指针传递
    {
        cout << "Property #" << i << ": $";
        cout << *pt << endl;
    }
}

//修改数组 
void revalue(double r, double * p_begin, double * p_end)
{

    for (double * pt = p_begin; pt != p_end; pt++)
        *pt *= r;
}

8.

a.

#include <iostream>

using namespace std;

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

void fill(double * pa);
void show(double * da);

int main()
{
    double expenses[Seasons];

    fill(&expenses[Seasons]);//注意传递地址 

    show(&expenses[Seasons]);

    return 0;

}

void fill(double * pa)
{
    for(int i = 0; i < Seasons; i++)
    {
        cout << "Enter " << *(p_season + i) << " expenses: ";
        cin >> pa[i];//注意这里pa[i]等价于*(pa+i),即数组名实际为一个指针 
    }   
}

void show(double * da)
{
    double total = 0.0;
    cout << "\nEXPENSES\n";
    for(int i = 0; i < Seasons; i++)
    {
        cout << *(p_season + i) << ": $" << da[i]<< endl;
        total += da[i];//解释同上 
    }   
    cout << "Total Expenses: $" << total << endl;  
} 

b.

#include <iostream>
struct expenses{
    double money;
};//定义结构 

using namespace std;

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

void fill(double * pa);
void show(double * da);

int main()
{
    expenses use[Seasons];//声明结构 

    fill(&use[Seasons].money);//注意传递地址 

    show(&use[Seasons].money);

    return 0;

}

//------------调用函数不需要修改--------------- 
void fill(double * pa)
{
    for(int i = 0; i < Seasons; i++)
    {
        cout << "Enter " << *(p_season + i) << " expenses: ";
        cin >> *(pa+i);//注意这里pa[i]等价于*(pa+i),即数组名实际为一个指针 
    }   
}

void show(double * da)
{
    double total = 0.0;
    cout << "\nEXPENSES\n";
    for(int i = 0; i < Seasons; i++)
    {
        cout << *(p_season + i) << ": $" << da[i]<< endl;
        total += da[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)//pa[]可以视作指针 
{
    int count = 0; 
    cout << "\nEnter the student information:" << endl;
    for(int i = 0; i < n ;i++)
    {
        cout << "Student #" << i+1 << ": " << endl;
        cout << "Enter the fullname: " ;    
        cin.getline(pa[i].fullname, SLEN);
        cout << "Enter the hobby: " ;
        cin.getline(pa[i].hobby, SLEN);
        cout << "Enter the ooplevel: " ;        
        cin >> pa[i].ooplevel;
        if(!cin)break;//非数字时提前终止输入 
        cin.get();
        count++;
    }
    cout<<"Enter end!" << endl << endl;             
    return count;   
}

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

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


void display3(const student pa[], int n)
{
    cout << "\nHere is the student information:" << endl;   
    for(int i = 0; i < n; i ++)
    {
    cout << "Student #" << i+1 << ": " << endl;
    cout << "The fullname: " << pa[i].fullname << endl; 
    cout << "The hobby: " << pa[i].hobby << endl;
    cout << "The ooplevel: " << pa[i].ooplevel << endl;                     
    }   
}

10.

#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);
double divide (double a, double b);

int main()
{
    double a, b;
    double (*pf[4])(double a, double b);
    pf[0] = add;
    pf[1] = subtract;
    pf[2] = multiply;
    pf[3] = divide;

    cout << "Enter two numbers: (q to quit)" << endl;
    while(cin >> a >> b)
    {
        for(int i = 0 ; i < 4 ; i++)
           cout << "The answer is: "<< (*pf[i])(a, b) << endl;          
    }
    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;       
}

double divide (double a, double b)
{   
    return a / b;       
}

猜你喜欢

转载自blog.csdn.net/weixin_41882882/article/details/81263318