#include <iostream>
using namespace std;
int gcd(int,int);
class CFraction
{private:
int nume;//分子
int deno;//分母
public:
CFraction(int nu = 0,int de = 1);//构造函数,初始化用
void set(int nu = 0,int de = 1);//置值,改变值时用
void intput();//按照"nu/de"的格式,如"5/2"的形式输入
void simplify();//化简(是分子分母没有公因子)
void amplify(int n);//放大n倍,如2/3放大五倍为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)
{
if (de != 0)
{
nume = nu;
deno = de;
}
else
{
cerr<<"分母不能为0"<<endl;
system("pause");
exit(0);
}
}
void CFraction::set(int nu,int de)
{
if(de != 0)
{
nume = nu;
deno = de;
}
}
void CFraction::intput()
{
int nu ,de;
char c;
while(1)
{
cout<<"请输入分子分母(m/n):"<<endl;
cin>>nume>>c>>deno;
if (c != '/')
cout<<"格式不对"<<endl;
else if(deno == 0)
cout<<"分母不能为0"<<endl;
else
break;
}
nume = nu;
deno = de;
}
void CFraction::simplify()
{
int n = gcd(deno ,nume);
nume = nume/n;
deno = deno/n;
}
void CFraction::amplify(int n)
{
nume*=n;
}
void output(int style = 0)
{
int i ,nu , de ,nume,deno;
switch (style)
{
case 0:
cout <<nume <<'/'<<deno<<endl;
break;
case 1:
i = gcd(deno,nume);
cout<<(nume/i)<<(deno/i)<<endl;
break;
case 2:
i = gcd(deno,nume);
nu = nume/i;
de =deno/i;
cout <<(nume/deno)<<"("<<(nume%deno)<<deno<<")"<<endl;
break;
case 3:
cout<<nume<<"/"<<deno<<endl;
}
}
int main()
{
CFraction c1;
c1.set(3,4);
c1.output(0);
system("pause");
return 0;
}
//求最大公约数
int gcd(int x,int y)
{
int r;
while (y != 0)
{
r = x%y;
x = y;
y = r;
}
return x;
}
第五周实验报告2
最新推荐文章于 2022-02-25 21:57:21 发布