1. 程式人生 > >C++ Primer 第五版第7章程式設計練習節選(函式指標陣列)

C++ Primer 第五版第7章程式設計練習節選(函式指標陣列)

問題描述:設計一個函式指標用於完成兩個數字(x, y)的"平均值"計算,並驗證:調和平均數<=幾何平均數<=算術平均數<=平方平均數,當且僅當x = y 是等號成立。

要求:1,(x, y)可從控制檯連續輸入;

           2,函式指標原型 double calculate(double x, double y, double (*pf)(double x, double y));

           3, 函式值初始化 double (*pf[4])(double x, double y).

程式碼實現:

#include<iostream>
#include<cmath>

using namespace std;

const int Arsize = 4;

double Hn(double x, double y);
double Gn(double x, double y);
double An(double x, double y);
double Qn(double x, double y);

double calculate(double x, double y, double(*pf)(double x, double y));

int main()
{
	double x, y;
	
	double(*pf[Arsize])(double x,double y);
	pf[0] = Hn;
	pf[1] = Gn;
	pf[2] = An;
	pf[3] = Qn;
	cout << "Enter two munbers(x, y) : ";
	while (cin >> x >> y)
	{
		cout << "The Hornmic mean of x and y is : " << (*pf[0])(x, y) << endl;
		cout << "The Geometic mean of x and y is : " << (*pf[1])(x, y) << endl;
		cout << "The Arithmetic mean of x and y is : " << (*pf[2])(x, y) << endl;
		cout << "The Quadratic mean of x and y is : " << (*pf[3])(x, y) << endl;
		cout << "Enter the next two numbers (Q or q to quit): ";
	}
	return 0;
}

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

double Hn(double x, double y)
{
	return 2 * x*y / (x + y);
}

double Gn(double x, double y)
{
	return sqrt(x*y);
}

double An(double x, double y)
{
	return (x + y) / 2;
}

double Qn(double x, double y)
{
	return sqrt((x*x + y * y) / 2);
}