码迷,mamicode.com
首页 > 其他好文 > 详细

A1088.Rational Arithmetic

时间:2019-02-08 23:34:16      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:bit   恶心   oid   main   abs   部分   总结   out   down   

题意

模拟分数的四则运算

思路分析

模拟,在输出过程中,若分子>分母,需要分离出整数部分与分数部分,并且如果项为负数需要带上()

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

struct fraction{
    ll up;  //分子 
    ll down;        //分母 
}a,b,result;

ll gcd(ll a,ll b){
    if(b == 0) return a;
    else return gcd(b,a%b); 
}

fraction simply(fraction a){            //对分子分母进行约分 
    if(a.down < 0) {            //如果输入分母是负数,统一为分子带符号,分母不带符号 
        a.up = -a.up;
        a.down = - a.down;
    }
    int GCD = gcd(abs(a.up),abs(a.down));
    a.up /= GCD;
    a.down /= GCD;
    return a;
}

void showResult(fraction a){
    a = simply(a);          //对a化简  
    if(a.up < 0) printf("(");           //如果是负数 
    if(a.down == 1) printf("%lld",a.up);            //如果分母为1 
    else if(a.up == 0) printf("0");             //如果分子为0 
    else if(abs(a.up) > abs(a.down))            //如果分子>分母,需要输出整数部分 
        printf("%lld %lld/%lld",a.up/a.down,abs(a.up) % a.down,a.down);
    else if(abs(a.up) == abs(a.down)) printf("%d",a.up/a.down);         //分子=分母 
    else 
        printf("%lld/%lld",a.up,a.down);            //分子<分母 
    if(a.up < 0) printf(")");
}

fraction Sum(fraction a,fraction b){
    result.up = a.up * b.down + a.down * b.up;
    result.down = a.down * b.down;
    return simply(result);
}

fraction Mul(fraction a,fraction b) {
    result.up = a.up * b.up;
    result.down = a.down * b.down;
    return simply(result);
}

fraction Del(fraction a,fraction b) {
    result.up = a.up * b.down - a.down * b.up;
    result.down = a.down * b.down;
    return simply(result);
}

fraction div(fraction a,fraction b) {
    result.up = a.up * b.down;
    result.down = a.down * b.up;
    return simply(result);
}

int main(void){
    scanf("%lld/%lld %lld/%lld",&a.up,&a.down,&b.up,&b.down);
    //加法 
    showResult(a);
    printf(" + ");
    showResult(b);
    printf(" = ");
    showResult(Sum(a,b));
    cout<<endl;
    
    //减法
    showResult(a);
    printf(" - ");
    showResult(b);
    printf(" = ");
    showResult(Del(a,b));   
    cout<<endl;
    
    //乘法
    showResult(a);
    printf(" * ");
    showResult(b);
    printf(" = ");
    showResult(Mul(a,b)); 
    cout<<endl;
    //除法
    showResult(a);
    printf(" / ");
    showResult(b);
    printf(" = ");
    if(b.up == 0) cout<<"Inf";
    else showResult(div(a,b)); 
    return 0;
}

总结

PAT 第一道题20分就这么难,这还考个球啊。屎山模拟,恶心到吐血,考虑细节较多

A1088.Rational Arithmetic

标签:bit   恶心   oid   main   abs   部分   总结   out   down   

原文地址:https://www.cnblogs.com/Western-Trail/p/10356855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!