.h
#include<>
class Fraction //声明分数类
{
public:
Fraction(int a=0,int b=1) //定义构造函数
{
numerator=a;
denominator=b;
}
friend istream& operator>>(istream &s,Fraction &t);
friend ostream& operator<<(ostream &s,Fraction &t); //声明重载输出函数
Fraction operator+(Fraction &c); //声明重载两个分数的加法运算符
Fraction operator+(int n); //声明重载分数和整数的加法运算符
Fraction operator-(Fraction &c); //声明重载两个分数的减法运算符
Fraction operator-(int n); //声明重载分数减整数的减法运算符
friend Fraction operator-(int n,Fraction &c);
Fraction operator*(Fraction &c); //声明重载两个分数的乘法运算符
Fraction operator*(int n); //声明重载分数与整数的乘法运算符
Fraction operator/(Fraction &c); //声明重载两个分数的除法运算符
Fraction operator/(int n); //声明重载分数除以整数的除法运算符
friend Fraction operator/(int n,Fraction &c);
Fraction predigest(); //声明约分函数
int getscore(int score);
private:
int numerator; //分子
int denominator; //分母
};
实现函数
#include<>
#include"" //加入类的头文件
Fraction Fraction::predigest() //约分函数//
{
int n,d,t,sign=1; //sign为分数符号标记
Fraction temp;
if(numerator<0&&denominator<0) //当分子、分母同为负时,分数符号标记sign=1
{
numerator=-numerator;
denominator=-denominator;
}
if(numerator>0&&denominator<0) //当分子为正,分母为负时,分数符号标记sign=-1
{
denominator=-denominator;
sign=-1;
}
if(numerator<0&&denominator>0) //当分子为负,分母为正时,分数符号标记sign=-1
{
numerator=-numerator;
sign=-1;
}
n=numerator;
d=denominator;
int r;
if(n<d) //辗转相除法求分子n与分母d最大公约数
{t=n;n=d;d=t;}
r=n%d;
while(r!=0)
{
n=d;
d=r; //d为最大公约数
r=n%d;
}
=sign*(numerator/d);
=denominator/d;
return temp;
}
Fraction Fraction::operator+(Fraction &c) //重载两个分数的加法运算符
{
Fraction temp;
=numerator*+denominator*;
=denominator*;
return temp;
}
Fraction Fraction::operator+(int n) //重载分数和整数的加法运算符
分数计算器 来自淘豆网m.daumloan.com转载请标明出处.