问题及代码:
/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:尚 月
* 完成日期:2015年 03 月 29 日
* 版 本 号: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=0,int d=1); //置值,改变值时用
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;
char c='/';
if(style==0)
cout<<nume<<c<<deno<<endl;
else if(style==1)
{
n=gcd(deno,nume);
cout<<"化简: "<<nume/n<<c<<deno/n<<endl;
}
else if(style==2)
cout<<"带分数:" <<nume/deno<<'('<<nume%deno<<c<<deno<<')'<<endl;
else if(style==3)
cout<<"近似值:" <<nume/double(deno)<<endl;
else
cout<<"默认:" <<nume<<c<<deno<<endl;
}
int main()
{
CFraction c1,c2,c3(2,3);
cout<<"请输入c1的值"<<endl;
c1.input();
c1.output(2);
cout<<endl;
cout<<"改变c1的值: "<<endl;
c1.set(5,8);
c1.output(1);
cout<<endl;
cout<<"c2: "<<endl;
c2.output(2);
cout<<endl;
cout<<"将c2化简: "<<endl;
c2.simplify();
c2.output(0);
cout<<endl;
cout<<"c3:"<<endl;
c3.output();
cout<<endl;
cout<<"将c3放大倍: "<<endl;
c3.amplify(3);
c3.output(0);
c3.output(3);
return 0;
}
运行结果:
学习总结:这个程序看起来很简单,实际做起来还是有点小障碍的,就是有一个小问题没有搞明白,在构造函数初始化的时候,为什么nu=0的时候就错了,nu=1的时候就是对的,求解答。。。