关于c++的编程问题
巴扎黑
巴扎黑 2017-04-17 11:48:48
0
2
698

(4) 定义一个分数类如下,要求实现各个成员函数,并在主函数中测试两个分数的加减乘除等运算。

cppclass Rational
{
public:
    Rational(int nn=1,int mm=1);          //构造函数
    Rational  R_add(Rational & A);    //加
    Rational  R_sub(Rational & A);    //减
    Rational  R_mul(Rational & A);    //乘
    Rational  R_p(Rational & A);    //除 
    void print();        //以简分数形式显示,注意约分
private:
void simple( );      //约分
    int m;            //分母
    int n;             //分子
};
巴扎黑
巴扎黑

reply all(2)
左手右手慢动作
cppclass Rational{
    public:
    Rational(int nn=1,int mm=1){
        this->n=nn;
        this->m=mm;
        this->simple();
    }; //构造函数
    Rational R_add(Rational & A){
        return *new Rational(this->n * A.m + A.n*this->m,this->m * A.m);
    }; //加
    Rational R_sub(Rational & A){
        return *new Rational(this->n * A.m - A.n*this->m,this->m * A.m);
    }; //减
    Rational R_mul(Rational & A){
        return *new Rational(this->n * A.n,this->m * A.m);
    }; //乘
    Rational R_p(Rational & A){
        return *new Rational(this->n * A.m,this->m * A.n);
    }; //除
    void print(){
        std::cout << this->n << "/" << this->m << endl;
    }; //以简分数形式显示,注意约分
    private:
    void simple( ){
        int limit = this->m > this->n ? this->n : this->m;
        for(int i=limit;i>1;i--){
            if(this->m%i==0 && this->n%i==0){
                this->m /= i;
                this->n /=i;
                break;
            }
        }
    }; //约分
    int m; //分母
    int n; //分子
};

How to use:

cpp    // 示例
    Rational* a= new Rational(4,10);  // 2/5
    Rational* b= new Rational(7,20);  // 7/20
    a->R_add(*b).print();  // 3/4
    a->R_sub(*b).print();  // 1/20
    a->R_mul(*b).print();  // 7/50
    a->R_p(*b).print();  // 8/7

Looking at this mentally handicapped problem, it should be like an assignment in the school C++ textbook. Brother, you also need someone to do your homework for you. Is this really good? ?

黄舟

haha A random search on the Internet for this computer question will yield results. Do you still need to ask? .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template