OOP习题(14)

一、函数题

1、分数

实现一个分数类Fraction,能读写“1/2”样子的分数。

hint:注意1e16的类型

函数接口定义:

class Fraction {...

请根据main自行推断。

裁判测试程序样例:

#include 
using namespace std;

/* 请在这里填写答案 */

int main(void)
{
    Fraction f1;
    Fraction f2;
    cin >> f1 >> f2;
    cout << f1+f2 << endl;
    cout << (double)(f1+f2) << endl;
    cout << f1-f2 << endl;
    cout << f1*f2 << endl;
    cout << f2/f1 << endl;
    double d;
    cin >> d;
    Fraction f((long long)(d*1e16), 1e16);
    cout << f << endl;
    f=0.5;
    cout << f << endl;
    Fraction*p = &f1;
    f1=*p;
    cout << f1 << endl;
    cin >> f1;
    f1 = f1*Fraction(2.0);
    cout << f1 << endl;
}

输入样例:

1/2
1/3
0.5
1/4

输出样例:

5/6
0.833333
1/6
1/6
2/3
1/2
1/2
1/2
1/2

代码解答: 

class Fraction
{
public:
    Fraction(){}
    Fraction(double m)
    {

        this->fenzi = (long long )m * 10;
        this->fenmu = 10;
        huajian(*this);
    }
    Fraction(long long x, double y)
    {
        this->fenzi = x;
        this->fenmu = (long long)y;
        huajian(*this);
    }
    operator double()
    {
        return (double)(1.0*this->fenzi / this->fenmu);
    }
    friend Fraction& huajian(Fraction& m);
    friend istream& operator>>(istream& in, Fraction& f);
    friend Fraction operator+(Fraction& x, Fraction& y);
    friend ostream& operator<<(ostream& out, Fraction m);
    friend Fraction operator-(Fraction& x, Fraction& y);
    friend Fraction operator*(Fraction& x, Fraction y);
    friend Fraction operator/(Fraction& x, Fraction& y);
    Fraction& operator=(Fraction x)
    {
        fenzi = x.fenzi;
        fenmu = x.fenmu;
        return *this;
    }
    Fraction& operator=(double x)
    {
        Fraction temp;
        temp.fenzi = (long long)(x * 10.0);
        temp.fenmu = 10;
        huajian(temp);
        *this = temp;
        return *this;
    }

private:
    long long  fenzi;
    long long  fenmu;
};
Fraction& huajian(Fraction& m)
{
    long long  c;
    long long max;
    long long a = m.fenzi;
    long long b = m.fenmu;
    if (a > b)
    {
        c = a % b;
        while (c != 0)
        {
            a = b;
            b = c;
            c = a % b;
        }
        max = b;
    }
    else if(a>(istream& in, Fraction& f)
{
    char c;
    in >> f.fenzi;
    in >>  c;
    in >> f.fenmu;
    return in;
}
ostream& operator<<(ostream& out, F

你可能感兴趣的:(面向对象程序设计,c++,学习)