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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章