#include<iostream>
#include<string>
#include<cmath>
#include<sstream>
//求最大公因数算法or欧几里德算法
// 递归版本
int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b, a % b);
}
// 迭代版本
int foreachGcd(int a,int b){
int remainder = 0;
while(b!=0){
remainder = a % b;
a = b;
b = remainder;
}
return a;
}
class Rational{
public :
Rational(){
numerator = 0;
denominator = 1;
};
Rational(int numerator, int denominator)
{
// 分母为零的情况
if (denominator == 0)
{
std::cout << "denominator can not be zero;" << std::endl;
}
// 分母和分子相同的情况,格式化为1/1
else if (numerator == denominator)
{
this->numerator = 1;
this->denominator = 1;
}
// 分子为零的情况,格式化为0/1
else if (numerator == 0)
{
this->numerator = 0;
this->denominator = 1;
}
// 分母小于零的情况,分子分母符号变化
else if (denominator < 0)
{
numerator = -1 * numerator;
denominator = -1 * denominator;
}
// 正常赋值构造
int gcf = 1;
if(numerator<0){
gcf = gcd(abs(numerator), denominator);
}else{
gcf = gcd(numerator, denominator);
}
//看看是否要约分
if(gcf!=1){
this->numerator = numerator / gcf;
this->denominator = denominator / gcf;
}else{
this->numerator = numerator;
this->denominator = denominator;
}
}
// toString函数
std::string getRational(){
std::ostringstream oss;
// 如果分子和分母相等,输出1
// 或者
// 如果分子为0,输出0
if(numerator==denominator||numerator==0){
oss << numerator << std::endl;
}else{
// 不然就正常输出
oss << numerator << "\n_____\n"
<< denominator << std::endl;
}
return oss.str();
}
Rational operator+(Rational &rational){
// 分母相同的情况,直接分子相加
if(rational.denominator==denominator){
return Rational(numerator + rational.numerator, denominator);
// 分母不同的情况,通分,然后再相加
}else{
int gcf = gcd(denominator, rational.denominator);
int newDenominator = denominator * rational.denominator / gcf;
int newNumerator = newDenominator / denominator * numerator + newDenominator / rational.denominator * rational.numerator;
return Rational(newNumerator, newDenominator);
}
}
private :
//符号位,暂时保留,没有使用,以后扩展功能可以用
// int sign=0;
// 分子
int numerator;
// 分母
int denominator;
};
int main(){
// std::cout << gcd(3, 6) << std::endl;
Rational r3;
Rational r1(1, 3), r2(2,3);
r3 = r1 + r2;
std::cout << r3.getRational() << std::endl;
}