当前位置: 代码迷 >> 综合 >> 【PAT】A1088 Rational Arithmetic (20分)(分数的四则运算(全))
  详细解决方案

【PAT】A1088 Rational Arithmetic (20分)(分数的四则运算(全))

热度:80   发布时间:2023-12-28 08:01:30.0

1088 Rational Arithmetic (20分)

题目链接

在这里插入图片描述

#include<iostream>
#include<cmath>
using namespace std;
#include<cstdlib>typedef long long ll;struct Fraction{
    ll up;ll down;
}fraction[2];char sign[4] = {
    '+', '-', '*', '/'};ll gcd(ll a, ll b)
{
    return b==0 ? a : gcd(b, a%b);
}//如果分母为负数,则分子分母同时取相反数;
//如果分子为0,则分母为1;
//如果分子分母有公约数,则化简 
Fraction reduction(Fraction a)
{
    if(a.down < 0){
    a.down = -a.down;a.up = -a.up;}else if(a.up == 0)a.down = 1;else{
    int d = gcd(abs(a.up), abs(a.down));a.up /= d;a.down /= d;}return a;
}Fraction add(Fraction a, Fraction b)
{
    Fraction temp;temp.up = a.up * b.down + a.down * b.up;temp.down = a.down * b.down;return reduction(temp);
}Fraction sub(Fraction a, Fraction b)
{
    Fraction temp;temp.up = a.up * b.down - a.down * b.up;temp.down = a.down * b.down;return reduction(temp);
}Fraction multi(Fraction a, Fraction b)
{
    Fraction temp;temp.up = a.up * b.up;temp.down = a.down * b.down;return reduction(temp);
}Fraction divide(Fraction a, Fraction b)
{
    Fraction temp;temp.up = a.up * b.down;temp.down = a.down * b.up;return reduction(temp);
}void print(Fraction a)
{
    a = reduction(a); if(a.up < 0)cout<<"(";if(a.down == 1)cout<<a.up;else if(a.up == 0)cout<<"0";else if(abs(a.up) > a.down)cout<<a.up/a.down<<" "<<abs(a.up) % (int)a.down<<"/"<<a.down;else{
    cout<<a.up<<"/"<<a.down;}if(a.up < 0)cout<<")";
}int main()
{
    for(int i=0;i<2;i++){
    scanf("%lld/%lld", &fraction[i].up, &fraction[i].down);}for(int i=0;i<4;i++){
    print(fraction[0]);cout<<" "<<sign[i]<<" ";print(fraction[1]);cout<<" = ";switch(i){
    case 0:print(add(fraction[0], fraction[1]));break;case 1:print(sub(fraction[0], fraction[1]));break;case 2:print(multi(fraction[0], fraction[1]));break;case 3:if(fraction[1].up == 0)cout<<"Inf"<<endl;elseprint(divide(fraction[0], fraction[1]));break;}if(i!=3)cout<<endl;}return 0;
}
  相关解决方案