_Corn_Cat_ 2022-06-05 18:02 采纳率: 57.1%
浏览 55
已结题

C++实现分数加法与乘法,输出结果只有一个

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

我的解答思路和尝试过的方法
输出1/6 -1/3
  • 写回答

1条回答 默认 最新

  • 浪客 2022-06-06 11:31
    关注
    
    friend ostream &operator<<(ostream &o,Fraction &f)
            {
                if(f.base!=0)//while(f.base!=0)
                {
                    f.Format();
    
                    if(f.base==1)
                        o<<f.top;
                    else //if(f.top<0)
                        o<<f.top<<"/"<<f.base;
                }
                else
                    o << "Error" << endl;
                return o;
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 7月7日
  • 已采纳回答 6月29日
  • 创建了问题 6月5日

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程