C++ premier plus 第六版 编程练习解答(第七章)

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

#include <iostream>

double average(double a, double b);

int main(void)
{
	using namespace std;
	double a;
	double b;
	double avr;
	cout << "Please enter two numbers: ";
	cin >> a >> b;
	while (a != 0 && b != 0)
	{
		avr = average(a, b);
		cout << "The average is: " << avr << endl;
		cout << "Please enter two numbers: ";
		cin >> a >> b;
	}
	cout << "Done!" << endl;
	return 0;
}

double average(double a, double b)
{
	double avr;
	avr = 2.0 * a * b / (a + b);
	return avr;
}

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

#include <iostream>

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

using namespace std;
const int Max=10;
	
int main()
{
	double aver;
	double arr[Max];
	cout << "Input " << Max << " scores: \n";
	cout << "# 1: ";
	int n = input(arr,Max);
	cout << "The score: ";
	show(arr, n);
	aver = average(arr, n);
	cout << "The average is: " << aver << endl;	
	return 0;
}

int input(double arr[], int n)
{
	int i = 0;
	while(cin >> arr[i] && ++i < n)
		cout << "# " << i+1 << ": ";
	return i;	
}

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

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

3.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 volume(box * a);
void show(box a);

int main()
{
	box A;
	cout << "The maker: ";
	cin.get(A.maker ,40).get();
	cout << "The height: ";
	cin >> A.height;
	cout << "The width: ";
	cin >> A.width;
	cout << "The length: ";
	cin >> A.length;
	
	volume(&A);
	show(A);
	return 0;
}

void show(box a)
{
	cout << "The maker: "  << a.maker<<endl;
	cout << "The height: " << a.height<<endl;
	cout << "The width: "  << a.width<<endl;
	cout << "The lenght: " << a.length<<endl;
	cout << "The volume: " << a.volume<<endl;
}

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

4.请修改程字请单7.4,以计算中得这种彩票头奖的几率。

#include <iostream>

long double probability(unsigned numbers, unsigned picks, unsigned s);

int main()
{
    using namespace std;
    double total, choices, s;
    cout << "Enter the total number of choices on the game card and\n"
            "the number of picks allowed:\n";
    while ((cin >> total >> choices>>s) && choices <= total)
    {
		cout << "You have one chance in ";
        cout << probability(total, choices, s);      // 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 s)
{
    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 * s;
    return result;
}

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

#include <iostream>
using namespace std;
long factorial(int n);
	
int main()
{
	cout<<"Please enter a number;";
	int n;
	long f;
	while(cin >> n && n >= 0)
	{
		f = factorial(n);
		cout << "The factorial is: " << f << endl;		
		cout << "Enter another number: ";
	 } 
	 cout << "Bye.\n";
	return 0;
}

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

6.程序将使用这些函数来填充数组然后显示数组;反转数组然后显示数组;反转数组中除第一个和最后一个元素之外的所有元素,然后显示数组。

#include <iostream>

using namespace std;

int Fill_arry(double num[], int n);
void Show_arry(double num[], int n);
void Reverse_arry(double num[], int n);
	
int main()
{
	int n;
	cout << "How many numbers: ";
	cin >> n;
	double num[n];
	cout << "The 1 number: ";
	n=Fill_arry(num, n);
	cout << "The numbers of the arry is: " << n << endl;
	Show_arry(num, n);
	Reverse_arry(num, n);
	Show_arry(num, n);
	Reverse_arry(num, n);
	double tmp = num[0];
	num[0] = num[n - 1];
	num[n - 1] = tmp;
	Show_arry(num, n);
	return 0;
}

int Fill_arry(double num[], int n)
{
	int i = 0;
	while(cin >> num[i] && ++i < n)
	{
		cout << "The " << i + 1 << " number: ";
	}
	return i;
}

void Show_arry(double num[], int n)
{
	cout << "The arry is: ";
	for(int i = 0; i < n; i++)
	{
		cout << num[i] << " ";
	}
	cout << endl;
}

void Reverse_arry(double num[], int n)
{
	for(int i = 0; i < n / 2; i++)
	{
		double tmp = num[i];
		num[i] = num[n - 1 - i];
		num[n - 1 - i] = tmp;
	}
}

7.修改程序清单7.7中的三个数组处理函数,使之使用两个指针参数来表示区间。

#include <iostream>

double *fill_array(double * ar_begin, double * ar_end);
void show_array(double * ar_begin, double * ar_end);  
void revalue(double r, double * ar_begin, double * ar_end);

int main()
{
    using namespace std;
    double properties[5];
    double *p;

    p = fill_array(properties, properties + 5);
    show_array(properties, p);
    if (properties != p)
    {
        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, p);
        show_array(properties, p);
    }
    cout << "Done." << endl;
    return 0;
}

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

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

void revalue(double r, double * ar_begin, double * ar_end)
{
	double *p;
    for (p = ar_begin; p!=ar_end; p++)
        *p *= r;
}

8.在不使用array类的情况下完成程序清单7.15所做的工作。编写两个这样的版本。
(a)使用const char *数组存储表示季度名称的字符串,并使用double输出存储开支。

#include <iostream>

using namespace std;

const int Seasons = 4;
const char * Snames[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 " << Snames[i] << " expenses: ";
        cin >> pa[i];
    }
}

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

(b)使用const char *数组存储表示季度名称的字符串,并使用一个结构,该结构只有一个成员,一个用于存储开支的double数组。

#include <iostream>
using namespace std;
const int Seasons = 4;
const char * Snames[Seasons] =
    {"Spring", "Summer", "Fall", "Winter"};

struct cost
{
	double expenses[Seasons];
};

void fill(cost *pa);
void show(cost da);
int main()
{
    cost money;
    fill(&money);
    show(money);
    return 0;
}

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

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

9.这个练习让您编写处理数组和结构的函数。

#include <iostream>
#include <cstring>
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 count = 0;
	for(int i = 0;i < n; i++)
	{
		cout << "student " << i + 1 << ":\n" << "fullname: ";
		cin.getline(pa[i].fullname, SLEN);
		if(strlen(pa[i].fullname) == 0)
			break;
		cout << "hobby: ";
		cin.getline(pa[i].hobby, SLEN);
		cout  <<"ooplevel:";
		cin >> pa[i].ooplevel;
		cin.get();
        count++;
	}
	cout << 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)
{
	for(int i = 0; i < n; i++)
	{
		cout << "The student " << i + 1 << ":\n";
		cout << "The fullname: " << pa[i].fullname << endl;	
		cout << "The hobby: " << pa[i].hobby << endl;
		cout << "The ooplevel: " << pa[i].ooplevel << endl;
	}
}
#include <iostream>
#include <string>
using namespace std;

double add (double x, double y);
double subtract (double x, double y);
double multiply (double x, double y);
double divide (double x, double y);
double calculate (double x, double y, double (*p)(double x, double y));
	
int main()
{
	double x,y;
	double (*pf[4])(double,double) = {add,subtract,multiply,divide};
	string name[4] = {"add","subtrcat","multiply","divide"};
	cout << "Enter two numbers: ";
	while(cin >> x >> y)
	{
		for(int i = 0;i < 4; i++)
		{
			cout << name[i] << ": " << calculate(x, y, pf[i]) << endl; 
		}
		cout << "Enter another two numbers: ";
	}
	cout << "Done.\n";
	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 divide (double x, double y)
{
	return x / y;
}
double calculate (double x, double y, double (*p)(double x, double y))
{
	return (*p)(x,y);
}
发布了35 篇原创文章 · 获赞 18 · 访问量 6803

猜你喜欢

转载自blog.csdn.net/acslsr/article/details/104146440