OJ分数的四则运算

Description

编写分数类Fraction,实现两个分数的加、减、乘和除四则运算。主函数已给定。

Input

每行四个数,分别表示两个分数的分子和分母,以0 0 0 0 表示结束。

Output

空格分隔的两个分数的减和除的结果。

Sample Input

1 2 -1 2
4 3 3 4
0 0 0 0

Sample Output

1 -1
7/12 16/9

#include <iostream>

using namespace std; class Fraction { private:     int fz,fm; public:     Fraction() {};     Fraction(int z,int m):fz(z),fm(m) {};     Fraction operator+(Fraction &f);     Fraction operator-(Fraction &f);     Fraction operator*(Fraction &f);     Fraction operator/(Fraction &f);     bool operator==(int n);     friend istream &operator>>(istream &input,Fraction &f);     void output();     void simplify(); }; Fraction Fraction::operator+(Fraction &f) {     return Fraction(fz*f.fm+fm*f.fz,fm*f.fm); } Fraction Fraction::operator-(Fraction &f) {     return Fraction(fz*f.fm-fm*f.fz,fm*f.fm); } Fraction Fraction::operator*(Fraction &f) {     return Fraction(fz*f.fz,fm*f.fm); } Fraction Fraction::operator/(Fraction &f) {     return Fraction(fz*f.fm,fm*f.fz); } istream&operator>>(istream&input,Fraction &f) {     input>>f.fz>>f.fm;     return input; } bool Fraction::operator==(int n) {     if(fz==0&&fm==0)         return true;     else         return false; } void Fraction::output() {     simplify();     if(fz%fm==0)         cout<<fz/fm;     else     {         if(fm>0)             cout<<fz<<"/"<<fm;         else             cout<<-fz<<"/"<<-fm;

    } } void Fraction::simplify() {

    int r,m=fz,n=fm;     while(n)     {         r=m%n;         m=n;         n=r;     }     fz/=m;     fm/=m; } int main()

{

    Fraction f1,f2,f3;

    while(cin>>f1>>f2)     {

        if(f1==0&&f2==0)

            break;

        f3=f1-f2;

        f3.output();         cout<<" ";         f3=f1/f2;

        f3.output();

        cout<<endl;

    }

    return 0;

}

 

学习总结:
流运算符的插入运算符<<与流体去运算符>>必须要用friend函数
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值