f(m,n) = 1+f(m,n-1) (m=n)
f(m,n-1)+f(m-n,n)
代码实现:
#include
int f(int m,int n)
{
if(m == 1)return 1;
if(n == 1)return 1;
if(m < n) return f(m,m);
if(m == n)return f(m,n-1) + 1;
return f(m,n-1) + f(m-n,n);
}
main()
{
int m,n;
printf("Please input m & n:\n");
printf("m = ");
scanf("%d",&m);
printf("n = ");
scanf("%d",&n);
printf("f(%d,%d)=%d\n",m,n,f(m,n));
}
2、
试用C++的类声明定义“复数”的抽象数据类型。要求
(1) 在复数内部用浮点数定义它的实部和虚部。
(2) 实现3个构造函数:缺省的构造函数没有参数;第二个构造函数将双精度浮点数赋给复数的实部,虚部置为0;第三个构造函数将两个双精度浮点数分别赋给复数的实部和虚部。
(3) 定义获取和修改复数的实部和虚部,以及+、-、*、/等运算的成员函数。
(4) 定义重载的流函数来输出一个复数。
本贴来自ZDNetChina中文社区 ,本贴地址:
//在头文件complex.h中定义的复数类
#ifndef _complex_h_
#define _complex_h_
#include
class comlex {
public:
complex ( ){ Re = Im = 0; } //不带参数的构造函数
complex ( double r ) { Re = r; Im = 0; } //只置实部的构造函数
complex ( double r, double i ) { Re = r; Im = i; } //分别置实部、虚部的构造函数
double getReal ( ) { return Re; } //取复数实部
double getImag ( ) { return Im; } //取复数虚部
void setReal ( double r ) { Re = r; } //修改复数实部
void setImag ( double i ) { Im = i; } //修改复数虚部
complex & operator = ( complex & ob) { Re = ob.Re; Im = ob.Im; } //复数赋值
complex & operator + ( complex & ob ); //重载函数:复数四则运算
complex & operator – ( complex & ob );
complex & operator * ( complex & ob );
complex & operator / ( complex & ob );
friend ostream & operator << ( ostream & os, complex & c ); //友元函数:重载<<
private:
double Re, Im; //复数的实部与虚部
};
#endif
//复数类complex的相关服务的实现放在C++源文件complex.cpp中
#include
#include
#include “complex.h”
complex & complex :: operator + ( complex & ob ) {
//重载函数:复数加法运算。
complex * result = new complex ( Re + ob.Re, Im + ob.Im );
return *result;
}
complex & complex :: operator – ( complex & ob ) {
//重载函数:复数减法运算
complex *result = new complex ( Re – ob.Re, Im – ob.Im );
return * result;
}
complex & complex :: operator * ( complex & ob ) {
//重载函数:复数乘法运算
complex *result =
new complex ( Re * ob.Re – Im * ob.Im, Im * ob.Re + Re * ob.Im );
return *result;
}
complex & complex :: operator / ( complex & ) {
//重载函数:复数除法运算
double d = ob.Re * ob.Re + ob.Im * ob.Im;
complex * result = new complex ( ( Re * ob.Re + Im * ob.Im ) / d,
( Im * ob. Re – Re * ob.Im ) / d );
return * result;
}
friend ostream & operator << ( ostream & os, complex & ob ) {
//友元函数:重载<<,将复数ob输出到输出流对象os中。
return os << ob.Re << ( ob.Im >= 0.0 ) ? “+” : “-” << fabs ( ob.Im ) << “i”;
}