📄 618.cpp
字号:
/*
618.cpp OperOver!Fraction.cpp
分数的四则运算
Written by Feng Rev.2004
*/
#include <iostream.h>
class Fraction;
long GCD(long a,long b); //最大公约数Greatest common Dividor最大公约数
long LCM(long a,long b); //最小公倍数Lowest common Multiple 最小公倍数
void Reduce(long &a,long &b); // 公约,化简
void DispOper(Fraction a,char c,Fraction b);
class Fraction
{
long x,y; //分数 x/y
public:
Fraction () {x=0;y=1;} //y must not =0
Fraction(long a,long b=1)
{
if(b<0) {a=-a; b=-b;}
else if (b==0) b=1;
x=a;y=b;
}
Fraction operator +(const Fraction&c);
Fraction operator -(const Fraction&c);
Fraction operator *(const Fraction&c);
Fraction operator /(const Fraction&c);
void Disp() { cout<<"("<<x<<"/"<<y<<") "; }
};
Fraction Fraction::operator+(const Fraction&c)
{
long a,b;
a = x*c.y + y*c.x; b =y*c.y;
Reduce(a,b);
return Fraction(a,b);
}
Fraction Fraction::operator -(const Fraction&c)
{
long a,b;
a = x*c.y - y*c.x; b =y*c.y;
Reduce(a,b);
return Fraction(a,b);
}
Fraction Fraction::operator *(const Fraction&c)
{
long a,b;
a = x*c.x ; b = y*c.y;
Reduce(a,b);
return Fraction(a,b);
}
Fraction Fraction::operator /(const Fraction&c)
{
long a,b;
a = x*c.y ; b = y*c.x;
Reduce(a,b);
return Fraction(a,b);
}
void DispOper(Fraction a,char c,Fraction b)
{
a.Disp(); cout << c;
b.Disp(); cout << " = ";
switch (c)
{
case int('+'): a=a+b; break;
case int('-'): a=a-b; break;
case int('*'): a=a*b; break;
case int('/'): a=a/b; break;
default: a=a+b; break;
}
a.Disp();
}
main()
{
Fraction b1(3,4);
Fraction b2(-5,6);
Fraction b3;
b3=b1+b2;
b3.Disp(); cout <<endl;
DispOper(b1,'+',b2); cout <<endl;
b3=b1-b2;
b3.Disp(); cout <<endl;
DispOper(b1,'-',b2);cout <<endl;
b3=b1*b2;
b3.Disp(); cout <<endl;
DispOper(b1,'*',b2); cout <<endl;
b3=b1/b2;
b3.Disp(); cout <<endl;
DispOper(b1,'/',b2); cout <<endl;
return 0;
}
long GCD(long a,long b)
{
long t;
if(a>b) {t=a;a=b;b=t;}//swap to a<b
while((t = (b%a)) != 0){b=a;a=t;}
return a;
}
long LCM(long a,long b)
{return (a*b/GCD(a,b)); }
void Reduce(long &a,long &b)
{
long gcd = GCD(a,b);
a = a/gcd;
b = b/gcd;
}
/*-
(-1/12)
(3/4) +(-5/6) = (-1/12)
(19/12)
(3/4) -(-5/6) = (19/12)
(-5/8)
(3/4) *(-5/6) = (-5/8)
(-9/10)
(3/4) /(-5/6) = (-9/10)
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -