C++实现分数的加法与乘法
#include<iostream>
using namespace std;
class Fraction
{
public:
Fraction()
{
top=1;
base=1;
}
Fraction(int t,int b)
{
top=t;
base=b;
}
void Format()
{
while(base!=0)
{
int n=MaxCo(top,base);
if(top==0)
{
base=1;
}
else if(base<0)
{
top=-top;
base=-base;
}
top=top/n;
base=base/n;
break;
}
}
int MaxCo(int a,int b)
{
int temp;
while(b!=0)
{
temp=a%b;
a=b;
b=temp;
}
return a>0?a:-a;
}
friend ostream&operator<<(ostream&o,Fraction&f)
{
while(f.base!=0)
{
f.Format();
if(f.base==1)
o<<f.top;
else if(f.top<0)
o<<f.top<<"/"<<f.base;
return o;
}
}
friend istream&operator>>(istream&i,Fraction&f)
{
i>>f.top>>f.base;
return i;
}
friend Fraction operator+(Fraction&f1,Fraction &f2)
{
return Fraction(f1.top*f2.base+f1.base*f2.top,f1.base*f2.base);
}
friend Fraction operator*(Fraction&f1,Fraction &f2)
{
return Fraction(f1.top*f2.top,f1.base*f2.base);
}
private:
int top;
int base;
};
int main()
{
Fraction a;
cin >> a;
int f, m;
cin >> f >> m;
Fraction b(f, m);
Fraction c, d;
c = a + b;
d = a * b;
cout << c << endl;
cout << d << endl;
return 0;
}
输入1 -2
2 3
输出
[空格]
-1/3