完成下面类的设计,并在main()函数中自行定义对象,调用各成员函数,完成基本的测试。
#include <iostream> using namespace std; class CFraction { private: int nume; // 分子 int deno; // 分母 int n, d; public: CFraction(int nu=0,int de=1); //构造函数,初始化用 void Set(int nu=0,int de=1); //置值,改变值时用 void input(); //按照"nu/de"的格式,如"5/2"的形式输入 void Simplify(); //化简(使分子分母没有公因子) void amplify(int n); //放大n倍,如2/3放大5倍为10/3 void output(int style=0); //输出:以8/6为例,style为0时,输出8/6; //style为1时,输出4/3; //style为2时,输出1(1/3),表示一又三分之一; //不给出参数和非1、2,认为是方式0 }; CFraction::CFraction( int nu, int de ) {} void CFraction::Set( int nu , int de ) { nume = nu; deno = de; } void CFraction::input() { cout << "按照nu/de的格式输出:" << nume << "/" << deno << endl; } void CFraction::Simplify() { for ( int i = nume; i > 0; i-- ) { if ( nume % i == 0) if ( deno % i == 0 ) { n = nume / i; d = deno / i; cout <<"化简后输出:"<< n << "/" << d << endl; break; } } } void CFraction::amplify( int n ) { nume = n * nume; cout << "放大" << n << "倍为" << nume << "/" << deno << endl; } void CFraction::output(int style) { switch(style) { case 1: cout << "化简后输出:"<< n << "/" << d << endl; break; case 2: if ( nume > deno ) { int q, p; q = n / d; p = n - q * d; cout << "X又X分之X形式输出" << q << "(" << p << "/" << d << ")" << endl; } else cout << n << "/" << d << endl; break; default: cout << "以原式输出" << nume << "/" << deno << endl; break; } } int main () { CFraction c; c.Set(8,6); c.input(); c.Simplify(); c.output(2); c.output(0); c.amplify(5); cout << endl; c.Set(126,18); c.input(); c.Simplify(); c.output(0); c.output(1); c.output(2); return 0; }