/*
* 程序的版权和版本声明部分:
* Copyright (c) 2013, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:任子仪
* 完成日期:2014年 4月 19日
* 版 本 号:v12.1
* 输入描述:无
* 问题描述:。
* 程序输出:
* 问题分析:略
* 算法设计:略
*/
#include<iostream>
using namespace std;
class CFraction
{
private:
int nume; // 分子
int deno; // 分母
int gcd(int m, int n);
public:
//构造函数及运算符重载的函数声明
CFraction(int nu=0,int de=1);
friend CFraction operator+(CFraction &c1, CFraction &c2);
friend CFraction operator-(CFraction &c1, CFraction &c2);
friend CFraction operator*(CFraction &c1, CFraction &c2);
friend CFraction operator/(CFraction &c1, CFraction &c2);
void display();
void simplify();
};
//重载函数的实现及用于测试的main()函数
CFraction::CFraction(int nu,int de)
{
nume=nu;
deno=de;
if(deno==0||nume==0)
return;
}
void CFraction::simplify()
{
int n=gcd(deno, nume);
deno/=n; // 化简
nume/=n;
}
int CFraction::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::display()
{
cout<<nume<<"/"<<deno<< endl;
}
CFraction operator+(CFraction &c1, CFraction &c2)
{
CFraction c;
c.deno=c1.deno*c2.deno;
c.nume=c1.nume*c2.deno+c2.nume*c1.deno;
c.simplify();
return c;
}
CFraction operator-(CFraction &c1, CFraction &c2)
{
CFraction c;
c.deno=c1.deno*c2.deno;
c.nume=c1.nume*c2.deno-c2.nume*c1.deno;
c.simplify();
return c;
}
CFraction operator*(CFraction &c1, CFraction &c2)
{
CFraction c;
c.deno=c1.deno*c2.deno;
c.nume=c1.nume*c2.nume;
c.simplify();
return c;
}
CFraction operator/(CFraction &c1, CFraction &c2)
{
CFraction c;
c.deno=c1.deno*c2.nume;
c.nume= c1.nume*c2.deno;
c.simplify();
return c;
}
int main()
{
CFraction c1(9,8),c2(9,10);
cout << "c1+c2=";
(c1 + c2).display();
cout << "c1-c2=";
(c1 - c2).display();
cout << "c1*c2=";
(c1 * c2).display();
cout << "c1/c2=";
(c1 / c2).display();
return 0;
}
示例图片: