计算机表示分数的三个规定:
- 0的形式为0/1
- 分母必须为正,符号放在分子上
- 分子分母绝对值的最大公约数为1
struct fraction{
int up, down;
int gcd(int x, int y){
return !y ? x : gcd(y, x%y);
}
void simplify(){
if(up == 0){ /// 规定0为0/1
down = 1;
}else{
if(down < 0){ /// 规定分母必须为正
up = -up;
down = -down;
}
int res = gcd(abs(up), down); /// 规定分子分母最大公约数为1
up /= res;
down /= res;
}
}
fraction(int up, int down=1): up(up), down(down){
simplify();
}
void operator+=(const fraction &another){
up = up*another.up + another.up*down;
down = down*another.down;
simplify();
}
};