美文网首页
C++语言复习2

C++语言复习2

作者: Cipolee | 来源:发表于2019-06-12 17:45 被阅读0次

    DATA 2019/6/12

    封装一个分数类Fract,用来处理分数功能和运算,支持以下操作:

    1. 构造:传入两个参数n和m,表示n/m;分数在构造时立即转化成最简分数。
    2. show()函数:分数输出为“a/b”或“-a/b”的形式,a、b都是无符号整数。若a为0或b为1,只输出符号和分子,不输出“/”和分母。

    你设计一个Fract类,使得main()函数能够运行并得到正确的输出。调用格式见append.cc

    append.cc

    #include <cstdio>
    int main()
    {
        int n, m;
        while(cin >> n >> m)
        {
            Fract fr(n, m);
            fr.show();
        }
    }
    

    思路:先在内部化简(分子为0的坑,分母为0的坑)
    使用函数抽象化,写一个最小公因子函数(得到的永远是正整数),赋值给属性是已经最简的分子分母。
    然后避开一些坑就行了

    sample input sample output
    1 3
    20 -15
    80 150
    -9 1
    6 6
    12 16
    -33 -48
    6 11
    0 -10
    1/3
    -4/3
    8/15
    -9
    1
    3/4
    11/16
    6/11
    0

    my code as follow

    #include<iostream>
    #include<cstdlib>
    #include<cmath>
    using namespace std;
    int lcm(int n,int m)
    {
        if(n==0||m==0)return 0;
       n=abs(n);
        m=abs(m);
        if(n>m)
        {
            int t=n;
            n=m;
            m=t;
        }
        if(m%n==0)
            return n;
        else
            return lcm(m%n,n);
    }
    

    相关文章

      网友评论

          本文标题:C++语言复习2

          本文链接:https://www.haomeiwen.com/subject/llfrfctx.html