C++Primer Plus笔记——第七章 函数—C++的编程模块及课后编程练习答案

目录

 

本章小结

程序清单

7.1  函数简单示例

7.2  函数原型与调用

7.3  多个参数的函数

7.4  多个参数的函数

7.5  参数为数组的函数

7.6  数组为参数的本质

7.7  多个参数为数组的函数

7.8  使用数组区间的函数

7.9  C-风格字符串做为参数

7.10  返回C-风格字符串的函数

7.11  传递和返回结构

7.12  处理结构的函数

7.13  传递结构的地址

7.14  处理string类的函数

7.15  处理array对象的函数

7.16  递归函数

7.17  包含多个递归调用的递归

7.18  函数指针

7.19  深入探讨函数指针

课后编程习题答案


本章小结


       函数是C++的编程模块。要使用函数,必须提供定义和原型,并调用该函数。函数定义是实现函数功能的代码:函数原型描述了函数的接口:传递给函数的值的数目和种类以及函数的返回类型。函数调用使得程序将参数传递给函数,并执行函数的代码。
       在默认情况下,C++函数按值传递参数。这意味着函数定义中的形参是新的变量,它们被初始化为函数调用所提供的值。因此,C++函数通过使用拷贝,保护了原始数据的完整性。
        C++将数组名参数视为数组第一个元素的地址。从技术上讲,这仍然是按值传递的,因为指针是原始地址的拷贝,但函数将使用指针来访问原始数组的内容。当且仅当声明函数的形参时,下面两个声明才是等价的:
typeName arr[];
typeName * arr;
       这两个声明都表明,arr是指向typeName的指针,但在编写函数代码时,可以像使用数组名那样使用arr来访问元素:arr[i]。即使在传递指针时,也可以将形参声明为const指针,来保护原始数据的完整性。由于传递数据的地址时,并不会传输有关数组长度的信息,因此通常将数组长度作为独立的参数来传递。另外,也可以传递两个指针(其中一个指向数组开头,另一个指向数组末尾的下一个元素),以指定一个范围,就像STL使用的算法一样。
        C++提供了3种表示C-风格字符串的方法:字符数组、字符串常量和字符串指针。他们的类型都是char*(char指针),因此被作为char*类型参数传递给函数。C++使用空值字符(\0)来结束字符串,因此字符串函数检测空值字符来确定字符串的结尾。
       C++还提供了string类,用于表示字符串。函数可以接受string对象作为参数以及将string对象作为返回值,string类的方法size()可用于判断其存储的字符串的长度。
        C++处理结构的方式与基本类型完全相同,这意味着可以按值传递结构,并将其用作函数返回类型。然而,如果结构非常大,则传递结构指针的效率将更高,同时函数能够使用原始数据。这些考虑因素也适用于类对象。
        C++函数可以是递归的,也就是说,函数代码中可以包括对函数本身的调用。
        C++函数名与函数地址的作用相同。通过将函数指针作为参数,可以传递要调用的函数的名称。
 

程序清单

 

7.1  函数简单示例

//calling.cpp -- defining,prototyping,and calling a function
#include "stdafx.h"
#include
void simple();//function prototype

int main()
{
	using namespace std;
	cout << "main() will call the simple() function:\n";
	simple();//function call
	cout << "main() is finished with the simple() function.\n";
	cin.get();
	return 0;
}

//fuction definition
void simple()
{
	using namespace std;
	cout << "I'm but a simple function.\n";
}

7.2  函数原型与调用

//protos.cpp -- using prototypes and fuction calls
#include "stdafx.h"
#include

void cheers(int);
double cube(double x);

using namespace std;

int main()
{
	cheers(5);
	cout << "Gibe me a number: ";
	double side;
	cin >> side;
	double volume = cube(side);
	cout << "A " << side << " foot cube has a volume of ";
	cout << volume << " cubic feet.\n";
	cheers(cube(2));
	return 0;
}

void cheers(int n)
{
	for (int i = 0; i < n; i++)
		cout << "Cheers! ";
	cout << endl;
}

double cube(double x)
{
	return x * x * x;
}

7.3  多个参数的函数

//twoarg.cpp -- a function with a arguments
#include "stdafx.h"
#include

void n_chars(char, int);

using namespace std;

int main()
{
	int times;
	char ch;

	cout << "Enter a character: ";
	cin >> ch;
	while (ch != 'q')
	{
		cout << "Enter an integer: ";
		cin >> times;
		n_chars(ch, times);
		cout << "\nEnter another character or press the q-key to quit: ";
		cin >> ch;
	}
	cout << "The value of times is " << times << ".\n";
	cout << "Bye\n";
	return 0;
}

void n_chars(char c, int n)
{
	while (n-- > 0)
		cout << c;
}

7.4  多个参数的函数

//lotto.cpp -- probability of winning
#include "stdafx.h"
#include

//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\nthe 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 number (q to quit): ";
	}
	cout << "bye\n";
	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;
}

7.5  参数为数组的函数

//arrfun1.cpp -- functions with an array argument
#include "stdafx.h"
#include

const int ArSize = 8;
int sum_arr(int arr[], int n);

int main()
{
	using namespace std; \
	int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };//some systems require preceding int with static to enable array initialization
	int sum = sum_arr(cookies, ArSize);
	cout << "Total cookies eaten: " << sum << "\n";
	return 0;
}

//return the sum of an integer array
int sum_arr(int arr[], int n)
{
	int total = 0;
	for (int i = 0; i < n; i++)
		total = total + arr[i];
	return total;
}

7.6  数组为参数的本质

//arrfun2.cpp -- functions with an array argument
#include "stdafx.h"
#include

const int ArSize = 8;
int sum_arr(int arr[], int n);

using namespace std;

int main()
{
	int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };
	cout << cookies << " = array address, " << sizeof cookies << " = sizeof cookies\n";
	int sum = sum_arr(cookies, ArSize);
	cout << "Total cookies eaten: " << sum << endl;
	sum = sum_arr(cookies, 3);
	cout << "First three eaters ate " << sum << " cookies.\n";
	sum = sum_arr(cookies + 4, 4);//cookies+4是第5个元素的地址
	cout << "Last four eaters ate " << sum << " cookies.\n";
	return 0;
}

int sum_arr(int arr[], int n)
{
	int total = 0;
	cout << arr << " = arr, " << sizeof arr << " = sizeof arr\n";
	for (int i = 0; i < n; i++)
		total = total + arr[i];
	return total;
}

7.7  多个参数为数组的函数

// arrfun3.cpp -- array functions and const
#include "stdafx.h"
#include 
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 termianated.\n";
			break;
		}
		else if (temp < 0)
			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;
}

7.8  使用数组区间的函数

//arrfun4.cpp -- functions with an array range
#include "stdafx.h"
#include

const int ArSize = 8;
int sum_arr(const int * begin, const int * end);

int main()
{
	using namespace std;
	int cookies[ArSize] = { 1,2,4,8,16,32,64,128 };
	//some systems require preceding int withe static to enable array initialization

	int sum = sum_arr(cookies, cookies + ArSize);
	cout << "Total cookies eaten: " << sum << endl;
	sum = sum_arr(cookies, cookies + 3);
	cout << "First three eaters ate " << sum << " cookies.\n";
	sum = sum_arr(cookies + 4, cookies + 8);
	cout << "Last four eaters ate " << sum << " cookies.\n";
	return 0;
}

//return the sum of an integer array
int sum_arr(const int * begin, const int * end)
{
	const int * pt;
	int total = 0;

	for (pt = begin; pt != end; pt++)
		total = total + *pt;
	return total;
}

7.9  C-风格字符串做为参数

//strgfun.cpp -- functions with a string argument
#include "stdafx.h"
#include

unsigned int c_in_str(const char * str, char ch);

int main()
{
	using namespace std;
	char mmm[15] = "minimum";//string in an array
	//some systems require preceding char with static to enable array initialization
	char const * wail = "ululate";//wail points to string

	unsigned int ms = c_in_str(mmm, 'm');
	unsigned int us = c_in_str(wail, 'u');
	cout << ms << " m characters in " << mmm << endl;
	cout << us << " u characters in " << wail << endl;
	return 0;
}

//this function counts the number of ch characters in the string str
unsigned int c_in_str(const char * str, char ch)
{
	unsigned int count = 0;

	while (*str)//quit when *str is '\0'
	{
		if (*str == ch)
			count++;
		str++;//move point to next char
	}
	return count;
}

7.10  返回C-风格字符串的函数

//strgback.cpp -- a function that returns a pointer to char
#include "stdafx.h"
#include

char * buildstr(char c, int n);

int main()
{
	using namespace std;
	int times;
	char ch;

	cout << "Enter a character: ";
	cin >> ch;
	cout << "Enter an integer: ";
	cin >> times;
	char *ps = buildstr(ch, times);
	cout << ps << endl;
	delete[] ps; //free memory
	ps = buildstr('+', 20); //reuse pointer
	cout << ps << "-DONE-" << ps << endl;
	delete[] ps;
	return 0;
}

//builds string made of n c characters
char * buildstr(char c, int n)
{
	char * pstr = new char[n + 1];
	pstr[n] = '\0';
	while (n-- > 0)
		pstr[n] = c;
	return pstr;
}



	return total;
}

void show_time(travel_time t)
{
	using namespace std;
	cout << t.hours << " hours, " << t.mins << " minutes\n";
}

7.11  传递和返回结构

//travel.cpp -- using structures with functions
#include "stdafx.h"
#include
struct travel_time
{
	int hours;
	int mins;
};
const int Mins_per_hr = 60;

travel_time sum(travel_time t1, travel_time t2);
void show_time(travel_time t);

int main()
{
	using namespace std;
	travel_time day1 = { 5,45 };
	travel_time day2 = { 4,55 };

	travel_time trip = sum(day1, day2);
	cout << "Two day total: ";
	show_time(trip);

	travel_time day3 = { 4,32 };
	cout << "Three day total: ";
	show_time(sum(trip, day3));

	return 0;
}

travel_time sum(travel_time t1, travel_time t2)
{
	travel_time total;

	total.mins = (t1.mins + t2.mins) % Mins_per_hr;
	total.hours = t1.hours + t2.hours + (t1.mins + t2.mins) / Mins_per_hr;
	return total;
}

void show_time(travel_time t)
{
	using namespace std;
	cout << t.hours << " hours, " << t.mins << " minutes\n";
}

7.12  处理结构的函数

//strctfun.cpp -- functions with astructure argument
#include "stdafx.h"
#include
#include

//structure declarations
struct polar
{
	double distance; //distance from origin
	double angle; //direction from origin
};
struct  rect
{
	double x; //horizontal distance from origin
	double y; //vertical distance from origin
};

polar rect_to_polar(rect xypos);
void show_polar(polar dapos);

int main()
{
	using namespace std;
	rect rplace;
	polar pplace;

	cout << "Enter the x and y values: ";
	while (cin >> rplace.x >> rplace.y) //slick use of cin
	{
		pplace = rect_to_polar(rplace);
		show_polar(pplace);
		cout << "Next two numbers (q to quit): ";
	}
	cout << "Done.\n";
	return 0;
}

//convert rectangular to polar coordinates
polar rect_to_polar(rect xypos)
{
	using namespace std;
	polar answer;

	answer.distance = sqrt(xypos.x*xypos.x + xypos.y * xypos.y);
	answer.angle = atan2(xypos.y, xypos.x);
	return answer;
}

//show polar coordinates, converting angle to degrees
void show_polar(polar dapos)
{
	using namespace std;
	const double Rad_to_deg = 57.29577951;

	cout << "distance = " << dapos.distance;
	cout << ", angle = " << dapos.angle * Rad_to_deg;
	cout << " degrees\n";
}

7.13  传递结构的地址

//strcptr.cpp -- functions with pointer to structure arguments
#include "stdafx.h"
#include
#include

//structure templates
struct polar
{
	double distance; //distance from origin
	double angle; //direction from origin
};
struct  rect
{
	double x; //horizontal distance from origin
	double y; //vertical distance from origin
};

void rect_to_polar(const rect * xypos,polar * pda);
void show_polar(const polar * pda);

int main()
{
	using namespace std;
	rect rplace;
	polar pplace;

	cout << "Enter the x and y values: ";
	while (cin >> rplace.x >> rplace.y) //slick use of cin
	{
		rect_to_polar(&rplace,&pplace);
		show_polar(&pplace);
		cout << "Next two numbers (q to quit): ";
	}
	cout << "Done.\n";
	return 0;
}

//convert rectangular to polar coordinates
void rect_to_polar(const rect * pxy,polar * pda)
{
	using namespace std;
	pda -> distance = sqrt(pxy -> x * pxy->x + pxy->y * pxy->y);
	pda -> angle = atan2(pxy -> y, pxy -> x);
}

//show polar coordinates, converting angle to degrees
void show_polar(const polar * pda)
{
	using namespace std;
	const double Rad_to_deg = 57.29577951;

	cout << "distance = " << pda -> distance;
	cout << ", angle = " << pda -> angle * Rad_to_deg;
	cout << " degrees\n";
}

7.14  处理string类的函数

//topfive.cpp -- handling an array of string object
#include "stdafx.h"
#include
#include
using namespace std;
const int SIZE = 5;

void display(const string sa[], int n);

int main()
{
	string list[SIZE];//an array holding 5string object
	cout << "Enter your " << SIZE << " favorite astronomical sights:\n";
	for (int i = 0; i < SIZE; i++)
	{
		cout << i + 1 << ": ";
		getline(cin, list[i]);
	}

	cout << "Your list:\n";
	display(list, SIZE);

	return 0;
}

void display(const string sa[], int n)
{
	for (int i = 0; i < n; i++)
		cout << i + 1 << ": " << sa[i] << endl;
}

7.15  处理array对象的函数

//arrobj.cpp -- functions with array objects (C++11)
#include "stdafx.h"
#include
#include
#include

using namespace std;

//constant data
const int Seasons = 4;
const arraySnames = { "Spring","Summer","Fall","Winter" };

//function to modify array object
void fill(array*pa);
//function that uses array object without modifying it
void show(array da);

int main()
{
	array expenses;
	fill(&expenses);
	show(expenses);
	return 0;
}

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

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

7.16  递归函数

//recur.cpp -- using recursion
#include "stdafx.h"
#include

void countdown(int n);

int main()
{
	countdown(4);
	return 0;
}

void countdown(int n)
{
	using namespace std;
	cout << "Counting down ... " << n << endl;
	if (n > 0)
		countdown(n - 1); //function calls itself
	cout << n << ": Kaboom!\n";
}

7.17  包含多个递归调用的递归

//ruler.cpp -- using recursion to subdivide a ruler
#include "stdafx.h"
#include
using namespace std;

const int Divs = 6;//the division of ruler
const int Len = 66;//the length of ruler   Len = 2 ^ Divs + 2

void subdibide(char ar[], int low, int high, int level);

int main()
{
	char ruler[Len];
	int i;
	for (i = 1; i < Len - 2; i++)
		ruler[i] = ' ';
	ruler[Len - 1] = '\0';
	int max = Len - 2;
	int min = 0;
	ruler[min] = ruler[max] = '|';
	cout << ruler << endl;
	for (i = 1; i <= Divs; i++)
	{
		subdibide(ruler, min, max, i);
		cout << ruler << endl;
		for (int j = 1; j < Len - 2; j++)
			ruler[j] = ' ';//reset to blank ruler
	}
	return 0;
}

void subdibide(char ar[], int low, int high, int level)
{
	if (level == 0)
		return;
	int mid = (high + low) / 2;
	ar[mid] = '|';
	subdibide(ar, low, mid, level - 1);
	subdibide(ar, mid, high, level - 1);
}

7.18  函数指针

​//fun_ptr.cpp -- pointers to functions
#include "stdafx.h"
#include

double betsy(int);
double pam(int);

//second argument is pointer to a type double function that takes a type int argument
void estimate(int lines, double (*pf)(int));

int main()
{
	using namespace std;
	int code;
	cout << "How many lines of code do you need? ";
	cin >> code;
	cout << "Here's Betsy's estimate:\n";
	estimate(code, betsy);
	cout << "Here's Pam's estimate:\n";
	estimate(code, pam);
	return 0;
}

double betsy(int lns)
{
	return 0.05*lns;
}

double pam(int lns)
{
	return 0.03*lns + 0.0004*lns*lns;
}

void estimate(int lines, double(*pf)(int))
{
	using namespace std;
	cout << lines << " lines will take ";
	cout << (*pf)(lines) << " hour(s)\n";//function pointer
}

​

7.19  深入探讨函数指针

//arfupt.cpp -- an array of function pointers
#include "stdafx.h"
#include

//various notations, same signatures
const double * f1(const double ar[], int n);
const double * f2(const double [], int);
const double * f3(const double *, int);

int main()
{
	using namespace std;
	double av[3] = { 1112.3, 1542.6, 2227.9 };

	const double *(*p1)(const double *, int) = f1;//pointer to a function
	auto p2 = f2;
	cout << "Using pointers to functions:\n";
	cout << " Address Value\n";
	cout << (*p1)(av, 3) << ": " << *(*p1)(av, 3) << endl;
	cout << p2(av, 3) << ": " << *p2(av, 3) << endl;

	const double *(*pa[3])(const double *, int) = { f1,f2,f3 };//pa an array of pointers
	auto pb = pa;
	cout << "\nUsing an array of pointers to functions:\n";
	cout << " Address Value\n";
	for (int i = 0; i < 3; i++)
		cout << pa[i](av, 3) << ": " << *pa[i](av, 3) << endl;
	cout << "\nUsing a pointer to a pointer to a function:\n";
	cout << " Address Value\n";
	for (int i = 0; i < 3; i++)
		cout << pb[i](av, 3) << ": " << *pb[i](av, 3) << endl;

	cout << "\nUsing pointers to an array of pointers:\n";
	cout << " Address Value\n";
	auto pc = &pa;//easy way to declare pc
	cout << (*pc)[0](av, 3) << ": " << *(*pc)[0](av, 3) << endl;

	const double *(*(*pd)[3])(const double *, int) = &pa;//hard way to declare pd
	const double *pdb = (*pd)[1](av, 3);
	cout << pdb << ": " << *pdb << endl;
	cout << (*(*pd)[2])(av, 3) << ": " << *(*(*pd)[2])(av, 3) << endl;
	return 0;
}

const double * f1(const double * ar, int n)
{
	return ar;
}

const double * f2(const double ar[], int)
{
	return ar + 1;
}

const double * f3(const double ar[], int)
{
	return ar + 3;
}

 

课后编程习题答案

 

//practice.cpp -- this is the practice of the seventh chapter
//运行时删除或注释多余部分
#include "stdafx.h"
#include

//practice-1
double t_av(double x, double y);
int main()
{
	using namespace std;
	double x, y;
	double result;
	cout << "Please enter two numbers (0 to stop): ";
	while ((cin >> x >> y) && x != 0 && y != 0)
	{
		result = t_av(x, y);
		cout << "The average is: " << result << endl;
		cout << "Please enter two numbers (0 to stop): ";
	}

	return 0;
}

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

//practice-2
const int MAX = 10;
using namespace std;
int fill_ar(double ar[], int limit);
void show_ar(const double ar[], int n);
double average(const double ar[], int n);

int main()
{
	double scores[MAX];
	int size = fill_ar(scores, MAX);
	show_ar(scores, size);
	if (size > 0)
		cout << "The average of scores is: " << average(scores, size) << endl;
	return 0;
}

int fill_ar(double ar[], int limit)
{
	double temp;
	int i;
	for (i = 0; i < limit; i++)
	{
		cout << "Enter score #" << i + 1 << ": ";
		cin >> temp;
		if (!cin)
		{
			cin.clear();
			while (cin.get() != '\n')
				continue;
			cout << "Bad input; enter a number: ";
			break;
		}
		if(temp < 0)//输入负数终止输入
			break;
		ar[i] = temp;
	} 
	return i;
} 

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

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

//practice-3
using namespace std;

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

void show(box);
box set();
box* calculate(box *);

int main()
{
	box a;
	a = set();
	box* pt = calculate(&a);
	show(a);
	return 0;
} 

box set()
{
	box b;
	cout << "please input the name of box :";
	cin >> b.maker;
	cout << "please input the height of box :";
	cin >> b.height;
	cout << "please input the width of box :";
	cin >> b. width;
	cout << "please input the length of box :";
	cin >> b.length;
	b.volume = 0.0;
	return b;
}

void show(box x)
{
	cout << endl << "The height of the box: " << x.height << endl
		<< "The width of the box: " << x.width << endl
		<< "The length of the box: " << x.length << endl
		<< "The volume of the box: " << x.volume << endl;
}

box* calculate(box* ps)
{
	(*ps).volume = (*ps).height * (*ps).length * (*ps).width;
	return ps;
}

//practice-4
using namespace std;
long double probability(unsigned, unsigned);


int main()
{
	double a, b, c;
	cout << "Enter the number of choices on the game card :";
	cin >> a;
	cout << "Enter the number of picks allowed in 1 field number:";
	cin >> b;
	cout << "Enter the number of choices on the game card in 2 field number:";
	cin >> c;
	while (cin)
	{
		if (b <= a)
		{
			long double chance;
			chance = probability(a, b)*c;
			cout << "You have one chance in "<< chance << " of wining.\n\n";
			cout << "Enter the number of choices on the game card :";
			cin >> a;
			cout << "Enter the number of picks allowed in 1 field number:";
			cin >> b;
			cout << "Enter the number of choices on the game card in 2 field number:";
			cin >> c;
			if (!cin)
				break;
		}
		else
			break;
	} 
	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 = result * n / p;
	return result;
}

//practice-5
long long int recure(int);

int main()
{
	using namespace std;
	int number;
	cout << "Enter a integer (q to stop): ";
	while (cin >> number)
	{
		long long int result = recure(number);
		cout << number << "! = " << result << endl;
		cout << "Next:";
	} 
	cout << "Done!" << endl;
	return 0;
}

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

//practice-6
using namespace std;
const int Asize = 10;
int Fill_array(double[], int);
void Show_array(double[], int);
double * Reverse_array(double[], int, int);
int main()
{
	double numbers[Asize];
	cout << "Please enter some numbers(less than ten): \n";
	int i = Fill_array(numbers, Asize);
	cout << "You've entered " << i << " numbers:\n";
	Show_array(numbers, i);
	cout << endl;
	double * pt = Reverse_array(numbers, 0, i);
	Show_array(pt, i);
	cout << endl;
	double * ps = Reverse_array(numbers, 1, i);
	Show_array(ps, i);
	cout << endl;
	return 0;
}

int Fill_array(double ar[], int size)
{
	int i;
	for (i = 0; i < Asize; i++)
	{
		if (cin >> ar[i])
			;
		else
			break;
	} 
	return i;
} 

void Show_array(double ar[], int size)
{
	for (int i = 0; i < size; i++)
		cout << ar[i] << " ";
}

double * Reverse_array(double ar[], int a, int size)
{
	cout << "Here are(is) the number(s) after reverse:\n";
	double temp;
	for (int i = a; i < size / 2; i++)
	{
		temp = ar[i];
		ar[i] = ar[size - i - 1];
		ar[size - i - 1] = temp;
	} 
	return ar;
}

//practice-7
using namespace std;
const int Max = 5;
void show_array(const double[], double *);
void revalue(double, double[], double *);
double * fill_array(double[], int);
int main()
{
	double properties[Max];
	double * p = fill_array(properties, Max);
	show_array(properties, p);
	if (p != &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, p);
		show_array(properties, p);
	} 
	cout << "Done.\n";
	return 0;
}

double * fill_array(double ar[], int n)
{
	double temp;
	int i;
	for (i = 0; i < n; 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;
	}
	double * pt = &ar[i - 1];
	return pt;
} 

void show_array(const double ar[], double * ps)
{
	const double * p = &ar[0];
	for (int i = 0; p != ps + 1; p++, i++)
	{
		cout << "Property #" << (i + 1) << ": $";
		cout << ar[i] << endl;
	}
} 

void revalue(double r, double ar[], double * ps)
{
	double * p = &ar[0];
	for (int i = 0; p != ps + 1; p++, i++)
		ar[i] *= r;
}

//practice-8a
using namespace std;
const char * Seasons[4] = { "Spring", "Summer", "Fall", "Winter" };
void fill(double *);
void show(double[]);
int main()
{
	double expenses[4];
	fill(expenses);
	show(expenses);
	return 0;
} 

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

void show(double ar[])
{
	double total = 0.0;
	cout << "\nEXPENSES\n";
	for (int i = 0; i < 4; i++)
	{
		cout << Seasons[i] << ": $" << ar[i] << endl;;
		total += ar[i];
	} 
	cout << "Total Expenses: $" << total << endl;
}

//practice-8b
using namespace std;
const char * Seasons[4] = { "Spring", "Summer", "Fall", "Winter" };
struct expenditure
{
	double expenses[4];
};
expenditure fill(expenditure);
void show(expenditure);
int main()
{
	expenditure a = { { 0.0 } };
	expenditure v = fill(a);
	show(v);
	return 0;
} 

expenditure fill(expenditure b)
{
	for (int i = 0; i < 4; i++)
	{
		cout << "Enter " << Seasons[i] << " expenses: ";
		cin >> b.expenses[i];
	} 
	return b;
} 

void show(expenditure b)
{
	double total = 0.0;
	cout << "\nEXPENSES\n";
	for (int i = 0; i < 4; i++)
	{
		cout << Seasons[i] << ": $" << b.expenses[i] << endl;
		total += b.expenses[i];
	} 
	cout << "Total Expenses: $" << total << endl;
}

//practice-9
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 * p, int num)
{
	int i;
	for (i = 0; i < num; i++)
	{
		cout << "Enter the fullname: ";
		cin.getline((p + i)->fullname, SLEN);
		cout << "Enter the hobby: ";
		cin.getline((p + i)->hobby, SLEN);
		cout << "Enter the ooplevel: ";
		cin >> (p + i)->ooplevel;
		if (!cin)
			break;
		else
			cin.get();
	} 
	return i;
} 

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

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

void display3(const student pa[], int num)
{
	for (int i = 0; i < num; i++)
	{
		cout << pa[i].fullname << " "
			 << pa[i].hobby << " "
			 << pa[i].ooplevel << endl;
	}
}

//practice-10
double calculate(double x, double y, double(*pf)(double, double));
double add(double x, double y);
double sub(double x, double y);
double mean(double x, double y);

int main()
{
	using namespace std;
	double a, b;
	double(*pf[3])(double, double) = { add, sub, mean };
	char * op[3] = { "add", "sub", "mean" };
	cout << "Enter pairs of numbers (q to quit): ";
	while (cin >> a >> b)
	{
		for (int i = 0; i < 3; i++)
		{
			cout << op[i] << ": " << a << " and " << b << " = "
				<< calculate(a, b, pf[i]) << endl;
		}
	}
}

double calculate(double x, double y, double(*pf)(double, double))
{
	return(*pf)(x, y);
}

double add(double x, double y)
{
	return x + y;
}

double sub(double x, double y)
{
	return x - y;
}

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

​

 

你可能感兴趣的:(●C++,C,primer,plus,习题答案)