第四周项目二 分数类的雏形

/*
 * Copyright (c) 2014, 烟台大学计算机学院
 * All rights reserved.
 * 文件名称:test.cpp
 * 作    者:刘佳琦
 * 完成日期:2015年 3 月 27 日
 * 版 本 号:v1.0
 *
 * 问题描述:C++中提供了多种基本的数据类型。实际上,这些远不能满足我们的需求,如复数(第10章的例子大多是处理复数),再如分数。我们可以自定义类支持这些数据类型。
  本任务将设计一个简单的分数类,完成对分数的几个运算。一则巩固基于对象编程的方法,二则也为运算符重载等积累些感性认识。
 * 程序输入:无
 * 程序输出:无
 */
#include<iostream>
#include<Cmath>
#include<cstdlib>
using namespace std;
int gcd(int m, int n);
class CFraction
{
private:
    int nume;  // 分子
    int deno;  // 分母
public:
    CFraction(int n=1,int d=1);   //构造函数,初始化用
    void set(int n,int d);    //置值,改变值时用
    void input();				//按照"nu/de"的格式,如"5/2"的形式输入
    void simplify();			//化简(使分子分母没有公因子)
    void amplify(int n);			//放大n倍,如2/3放大5倍为10/3
    void output(int style=0);
};

CFraction::CFraction(int n,int d)
{
        nume=n;
        deno=d;
}

void CFraction::set(int n,int d)  
{
        nume=n;
        deno=d;
}

void CFraction::input()	
{
    int n,d;
    char c;
    cin>>n>>c>>d;
    nume=n;
    deno=d;
}

void CFraction::simplify()
{
    int n=gcd(deno,nume);
    deno/=n;   
    nume/=n;
}


int gcd(int m, int n) 
{
    int r;
    if (m<n)
    {
        r=m;
        m=n;
        n=r;
    }
    while(r=m%n)  // 求m,n的最大公约数
    {

        m=n;
        n=r;
    }
    return n;
}

void CFraction::amplify(int n)  
{
    nume*=n;
}
void CFraction::output(int style)
{
    int n;
    if(style==0)
        cout<<nume<<'/'<<deno<<endl;
    else if(style==1)
    {
        n=gcd(deno,nume);
        cout<<"化简: "<<nume/n<<'/'<<deno/n<<endl;   
    }
    else if(style==2)
        cout<<"带分数:" <<nume/deno<<'('<<nume%deno<<'/'<<deno<<')'<<endl;
    else if(style==3)
        cout<<"近似值:" <<nume/double(deno)<<endl;
    else
        cout<<"默认:" <<nume<<'/'<<deno<<endl;
}
int main()
{
    CFraction c1,c2,c3(2,3);
    cout<<"请输入c1的值"<<endl;
    c1.input();
    c1.output(2);
    cout<<"改变c1的值: "<<endl;   
    c1.set(5,8);
    c1.output(1);
    cout<<"c2: "<<endl;
    c2.output(2);
    cout<<"将c2化简: "<<endl;
    c2.simplify();
    c2.output(0);
    cout<<"c3:"<<endl;
    c3.output();
    cout<<"将c3放大倍: "<<endl;
    c3.amplify(3);
    c3.output(0);
    c3.output(3);
    return 0;
}

运行结果:


学习心得:

这个程序做的时间比较长,主要是辗转相除法记错了,然后各种失误,程序直接出问题关闭,之前一直找不到原因,后面根据贺老的博客对比修改,才发现问题所在,单步的时候也没细心,觉得那里是正确的= = 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值