zoukankan      html  css  js  c++  java
  • 运算符重载

    请定义一个分数类,拥有两个整数的私有数据成员,分别表示分子和分母(分母永远为正数,符号通过分子表示)。 重载运算符加号"+",实现两个分数的相加,所得结果必须是最简分数。

    输入:

    第一行的两个数 分别表示 第一个分数的分子和分母(分母不为0)。 第二行的两个数 分别表示 第二个分数的分子和分母。

    输出:

    第一个数表示分子,第二个数表示分母(若分数代表的是整数,则不输出分母)。

    输入样例:

    1  5
    2  5
     

    输出样例:

    3 5
     

    正确代码:

    #include<iostream>
    #include<math.h>
    using namespace std;
    class Fs{
        int fz,fm;
        public:
            void display();
            Fs(int x = 0, int y = 0);
            
    
               Fs operator+(Fs &op2)
            {
                int max = (this->fm > op2.fm) ? this->fm : op2.fm;
                do
                {
                    if (max % this->fm == 0 && max % op2.fm == 0)
                    {
                        break;
                    }
                    else
                        ++max;
    
                } while (true);
                 Fs temp;
                this->fz *= max / this->fm;
                op2.fz *= max / op2.fm;
                this->fz += op2.fz;
                temp.fz=this->fz;
                temp.fm=max;
                max = 1;
                for (int i = 1; i <= abs(this->fz); i++)
                {
                    if (temp.fz % i == 0 && temp.fm%i == 0)
                        max = i;
                }
                 
                temp.fm /=  max;
                temp.fz/=   max;
                return temp;
            }
    };
    Fs::Fs(int x,int y){
        fz = x;
        fm = y;
    }
    void Fs::display(){
        cout << fz;
        
        if(fm!=1&&fz!=0)
            cout << " " << fm;
    }
    int main(){
         
        int a[4];
        cin >> a[0] >> a[1] >> a[2] >> a[3];
        Fs x1(a[0],a[1]), x2(a[2],a[3]),x3;
        x3 = x1 + x2;
        x3.display();
    }
       
    
  • 相关阅读:
    dubbo-admin 2.0安装部署
    一文多发神器
    springboot整合druid踩坑记录
    thymeleaf中的重定向的绝对路径问题
    路径问题
    sp_executesql介绍和使用
    java.net.UnknownHostException: api.weixin.qq.com解决办法
    调用百度地图示例
    浅析分布式架构
    城乡医保用户角色未分配修改
  • 原文地址:https://www.cnblogs.com/pluie/p/12672595.html
Copyright © 2011-2022 走看看