📄 fraction.cpp
字号:
#include<math.h>
#include<stdlib.h>
#include<iostream.h>
#include"Fraction.hpp"
int hcf(int u,int v) //用辗转相除法求u,v的最大公约数
{
int t,r;
if(v>u)
{t=u;u=v;v=t;}
while((r=u%v)!=0)
{u=v;v=r;}
return v;
}
int lcd(int u,int v,int h) //求u,v的最小公倍数
{
int a;
a=u*v/h;
return a;
}
Fraction::Fraction(int a,int b) //输入分数
{
if(b==0)
cout<<"Input error!Please input it again!"<<"\n";
else {deno=a; nume=b; return;}
}
Fraction::Fraction(const Fraction& other)
{
deno=other.deno;
nume=other.nume;
return;
}
Fraction Fraction::mins1() //用辗转相除法化简
{
int t;
Fraction temp;
t=hcf(deno,nume);
if(t==0) temp=0;
else {temp.deno=deno/t;
temp.nume=nume/t;}
return temp;
}
Fraction Fraction::mins2() //用分解因式化简
{
int i,j,k,l,m;
Fraction temp;
if(deno<nume)
{for(i=2;i<=deno;i++)
{if(deno%i==0) k=i;
for(j=2;j<=nume;j++)
if(nume%j==0) l=j;
if(k==l) m=k; else m=1;
}
}
else
{for(i=2;i<=nume;i++)
{if(nume%i==0) k=i;
for(j=2;j<=deno;j++)
if(deno%j==0) l=j;
if(k==l) m=k; else m=1;
}
}
if(m==0) temp=0;
else {temp.deno=deno/m;
temp.nume=nume/m;}
return temp;
}
Fraction Fraction::operator +(const Fraction& other)
{
int t,r;
Fraction temp;
t=hcf(deno,other.deno);
r=lcd(deno,other.deno,t);
temp.nume=nume*r/deno+other.nume*r/other.deno;
temp.deno=r;
temp.mins1();
return temp;
}
Fraction Fraction::operator -(const Fraction& other)
{
int t,r;
Fraction temp;
t=hcf(deno,other.deno);
r=lcd(deno,other.deno,t);
temp.nume=nume*r/deno-other.nume*r/other.deno;
temp.deno=r;
temp.mins1();
return temp;
}
Fraction Fraction::operator *(const Fraction& other)
{
Fraction temp;
temp.deno=deno*other.deno;
temp.nume=nume*other.nume;
temp.mins1();
return temp;
}
Fraction Fraction::operator /(const Fraction& other)
{
Fraction temp;
temp.deno=deno*other.nume;
temp.nume=nume*other.deno;
temp.mins1();
return temp;
}
Fraction Fraction::operator =(const Fraction& other)
{
deno=other.deno;
nume=other.nume;
return *this;
}
int Fraction::operator <(const Fraction& other)//求较小的分数
{
int t,r;
t=nume*other.deno;
r=deno*other.nume;
if(t<=r) return 1;
else return 0;
}
int Fraction::operator >(const Fraction& other)//求较大的分数
{
int t,r;
t=nume*other.deno;
r=deno*other.nume;
if(t>=r) return 1;
else return 0;
}
int Fraction::operator ==(Fraction& other)
{
if(deno*other.nume==nume*other.deno)
return 1;
else
return 0;
}
void Fraction::change(double c) //实现小数化分数
{
cout<<"请数一下小数的位数,用i表示!"<<"\n";
Fraction temp;
int i;
cout<<"请输入i:";
cin>>i;
temp.deno=int(pow(10,i));temp.nume=int(c*pow(10,i));
temp=temp.mins1();
cout<<"The result is:";
cout<<temp; cout<<"\n";
}
ostream& operator <<(ostream& stream,Fraction& obj)
{
stream<<obj.nume<<"/"<<obj.deno;
return stream;
}
istream& operator >>(istream& stream,Fraction& obj)
{
char a;
stream>>obj.nume;
stream>>a;
stream>>obj.deno;
return stream;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -