头文件:
#ifndef Rational_H
#define Rational_H
class Rational
{
private:
int numerator;
int denominator;
public:
Rational();
Rational(int , int );
Rational simplification(Rational&);
Rational addition(Rational& , Rational& );
Rational subtraction(Rational& , Rational& );
Rational multiplication(Rational& a, Rational& b);
Rational division(Rational& a, Rational& b);
void showvalue1();//分数形式展现
void showvalue2();//有理数形式展现
};
#endif
定义类的文件:
#include<math.h>
Rational::Rational() :numerator(1), denominator(1)
{
}
Rational::Rational(int a, int b):numerator(a), denominator(b)
{
Rational::simplification(*this);
}
Rational Rational::simplification(Rational&a)
{
int mini = std::min(numerator, denominator);
for (int i = mini; i > 0; i--)
{
if (numerator % i == 0 && denominator % i == 0)
{
numerator /= i;
denominator /= i;
break;
}
}
return a;
}
Rational Rational::addition(Rational&a, Rational&b)
{
this->numerator = a.numerator * b.denominator + a.denominator * b.numerator;
this->denominator = a.denominator * b.denominator;
Rational::simplification(*this);
return *this;
}
Rational Rational::subtraction(Rational& a, Rational& b)
{
this->numerator = a.numerator * b.denominator - a.denominator * b.numerator;
this->denominator = a.denominator * b.denominator;
Rational::simplification(*this);
return *this;
}
Rational Rational::multiplication(Rational& a, Rational& b)
{
this->numerator = a.numerator * b.numerator;
this->denominator = a.denominator * b.denominator;
Rational::simplification(*this);
return *this;
}
Rational Rational::division(Rational& a, Rational& b)
{
this->numerator = a.numerator * b.denominator;
this->denominator = a.denominator * b.numerator;
Rational::simplification(*this);
return *this;
}
void Rational::showvalue1()
{
std::cout << numerator << "/" << denominator<<std::endl;
}
void Rational::showvalue2()
{
double value = (double)numerator / denominator;
std::cout << value << std::endl;
}
一个demo:
#include"head.h"
int main()
{
//测试
Rational x(16, 12);
Rational y(4, 9);
Rational a1;
Rational a2;
Rational a3;
Rational a4;
a1.addition(x, y);
a2.subtraction(x, y);
a3.multiplication(x, y);
a4.division(x, y);
a1.showvalue1();
a2.showvalue1();
a3.showvalue1();
a4.showvalue1();
a1.showvalue2();
a2.showvalue2();
a3.showvalue2();
a4.showvalue2();
}