码迷,mamicode.com
首页 > 编程语言 > 详细

第十七周oj刷题——Problem B: 分数类的四则运算【C++】

时间:2015-07-02 14:08:10      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:c++   class   iostream      namespace   

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

/* All rights reserved.  
 * 文件名称:test.cpp  
 * 作者:陈丹妮  
 * 完成日期:2015年 7 月 2 日  
 * 版 本 号:v1.0  
 */  
#include <iostream>
using namespace std;
class Fraction
{
private:
    int x;
    int y;
    int e;
public:
    Fraction(int a=0,int b=1):x(a),y(b)
    {
        e=0;
    }
    friend istream& operator>>(istream& input,Fraction &f);
    bool operator ==(int a);
    void output();
    Fraction operator -(Fraction &f1);
    Fraction operator /(Fraction &f1);
};
istream& operator>>(istream& input,Fraction &f)
{
    input>>f.x>>f.y;
    return input;
}
bool Fraction::operator==(int a)
{
    if(x==a)
        return true;
    else
        return false;
}
Fraction Fraction::operator -(Fraction &f1)
{
    Fraction f;
    f.x=x*f1.y-f1.x*y;
    f.y=y*f1.y;

    return f;

}
Fraction Fraction::operator /(Fraction &f1)
{
    Fraction f;
    f.x=x*f1.y;
    f.y=y*f1.x;
    return f;
}
void Fraction::output()
{
    int r,m=x,n=y,t;
    if(m<n)
    {
        t=n;
        n=m;
        n=t;
    }
    while(n!=0)
    {
        r=m%n;
        m=n;
        n=r;
    }
    if(y==m)
        cout<<x/m;
    else if(x/m<0&&y/m<0)
        cout<<(-1)*x/m<<'/'<<(-1)*y/m;
    else if(y/m<0)
        cout<<-x/m<<'/'<<-y/m;
        else
cout<<x/m<<'/'<<y/m;

    if(e==0)
        cout<<" ";
    e++;
}

int main()
{
    Fraction f1,f2,f3;
    while(cin>>f1>>f2)
    {
        if(f1==0&&f2==0)
            break;
        f3=f1-f2;
        f3.output();
        f3=f1/f2;
        f3.output();
        cout<<endl;
    }
    return 0;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。

第十七周oj刷题——Problem B: 分数类的四则运算【C++】

标签:c++   class   iostream      namespace   

原文地址:http://blog.csdn.net/nufangdongde/article/details/46725161

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!