自定义分数类

/*
* Copyright (c) 2012, 烟台大学计算机学院
* All rights reserved.
* 作    者:庄子豪
* 完成日期:2013 年  3月29 日
* 版 本 号:v1.0
*
* 输入描述:
* 问题描述:
* 程序输出:
* 问题分析:
 *算法设计:

#include<iostream>
using namespace std;
class Cfraction
{
	private:
		int nume;//分子
		int deno;//分母
	public:
		Cfraction()//构造函数,初始化用
		{
			nume=0;
			deno=1;
		}
		void set(int nu,int de);//置值,改变值时用
		void input();//按照“nu/de”的形式输入
		void simplify();//化简(使分子分母没有公因子)
		void amplify(int n);//放大N倍 如2/3 放大五倍为10/3
		void out_put(int style=0);//输出:以8/6为例 style为0时 原样输出8/6
		//style为1时 输出化简后的形式 4/3
		//style为2时 输出1(1/3)形式,表示一又三分之一
		//style为3时 输出小数形式1.3333
		//不给出参数和非1.2.3,认为方式0

};
void Cfraction::set(int nu,int de)
{
	nume=nu;
	deno=de;
}
void Cfraction::input()
{
	char c;
	int nu,de;
	while(1)
	{
		cout<<"请按照(nu/de)的形式输入分数:";
		cin>>nu>>c>>de;
		set(nu,de);
		if(c!='/')
			cout<<"非法格式,请重新输入!";
		else
			break;
	}
	

}
void Cfraction::simplify()
{
	int max=0;
	if(nume>deno)
	{
		max=deno;
	}else{
		max=nume;
	}
	if(deno%max==0 && nume%max==0)
	{
		
	}else{
		while(deno%max!=0||nume%max!=0)
		{
			max--;
		}
	}
	deno=deno/max;
	nume=nume/max;
}
void Cfraction::amplify(int n)
{
	nume=nume*n;
}
void Cfraction::out_put(int style)
{
	int a;
	if(style!=1&&style!=2&&style!=3)
	{
		style=0;
	}
	switch(style)
	{
	case 0:
		cout<<nume<<"/"<<deno<<endl;
		break;
	case 1:
		simplify();
		cout<<nume<<"/"<<deno<<endl;
		break;
	case 2:
		a=nume/deno;
		nume=nume%deno;
		simplify();
		cout<<a<<"("<<nume<<"/"<<deno<<")";
		break;
	case 3:
		cout<<double(nume/(deno*1.0))<<endl;
		break;
	}
}
void main(void)
{
	int n,style;
	Cfraction C;
	C.input();
	cout<<"请输入分数放大的倍数:";
	cin>>n;
	C.amplify(n);
	cout<<"请输入输出的类型(0.1.2.3):";
	cin>>style;
	C.out_put(style);
}


 

 

不容易,眼睛快瞎了!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值