标题: c++运算符重载
作者: vanwoos @Ta
时间: 2015-05-04
翘了n节课之后突然听说要交作业?
题目就是加法运算符的重载计算分数
#include <iostream>
#include <stdio.h>
using namespace std;
class fraction{
public:
int m;//分子
int d;//分母
fraction (int m,int d)
{
this->m=m;
this->d=d;
}
};
fraction simplified(fraction a)
{
//return a;
int x;
int i;
x=(a.m>0 && a.d<0 || a.m<0 && a.d>0)?-1:1;
a.m=(a.m<0)?-a.m:a.m;
a.d=(a.d<0)?-a.d:a.d;
int min=(a.m>a.d)?a.d:a.m;
for(i=min;i>0;--i)
{
if(a.m%i==0 && a.d%i==0)
{
break;
}
}
return fraction(x*(a.m/i),a.d/i);
}
fraction operator+(fraction a,fraction b)
{
return simplified(fraction(a.m*b.d+b.m*a.d,a.d*b.d));
}
fraction operator-(fraction a,fraction b)
{
return simplified(fraction(a.m*b.d-b.m*a.d,a.d*b.d));
}
fraction operator*(fraction a,fraction b)
{
return simplified(fraction(a.m*b.m,a.d*b.d));
}
fraction operator/(fraction a,fraction b)
{
return a*fraction(b.d,b.m);
}
int main()
{
fraction a(-11,3),b(2,3);
fraction c=a+b;
fraction d=a-b;
fraction e=a*b;
fraction f=a/b;
cout <<a.m<<"/"<<a.d<<"+"<<b.m<<"/"<<b.d<<"="<<c.m<<"/"<<c.d<<endl;
cout <<a.m<<"/"<<a.d<<"-"<<b.m<<"/"<<b.d<<"="<<d.m<<"/"<<d.d<<endl;
cout <<a.m<<"/"<<a.d<<"*"<<b.m<<"/"<<b.d<<"="<<e.m<<"/"<<e.d<<endl;
cout <<a.m<<"/"<<a.d<<"÷"<<b.m<<"/"<<b.d<<"="<<f.m<<"/"<<f.d<<endl;
return 0;
}
[隐藏样式|查看源码]