clipboard.png
和之前那题一样,只不过是四册运算:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef long long ll;
struct node{
    ll up;
    ll down;
};

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

node reflesh(node a){
    if(a.down<0){
        a.down=-a.down;
        a.up=-a.up;
    }
    if(a.up==0){
        a.down=1;
    }else{
        int d;
        if(abs(a.up)>a.down){
            d=gcd(abs(a.up),a.down);
        }else{
            d=gcd(a.down,abs(a.up));
        }
        a.up/=d;
        a.down/=d;
    }
    return a;
}

node add(node a,node b){
    node result;
    result.down=a.down*b.down;
    result.up=a.up*b.down+b.up*a.down;
    return reflesh(result);
}
node minl(node a,node b){
    node result;
    result.down=a.down*b.down;
    result.up=a.up*b.down-b.up*a.down;
    return reflesh(result);
}
node doub(node a,node b){
    node result;
    result.down=a.down*b.down;
    result.up=a.up*b.up;
    return reflesh(result);
}
node mult(node a,node b){
    node result;
    result.down=a.down*b.up;
    result.up=a.up*b.down;
    return reflesh(result);
}

void output(node result){
    result=reflesh(result);
    if(result.up<0)
        printf("(");
    if(result.down==1){
        printf("%lld",result.up);
    }else if(abs(result.up)>result.down){
        printf("%lld %lld/%lld",result.up/result.down,abs(result.up)%result.down,result.down);
    }else{
        printf("%lld/%lld",result.up,result.down);
    }
    if(result.up<0)
        printf(")");
}

int main(){
    node a,b;
    scanf("%lld/%lld %lld/%lld",&a.up,&a.down,&b.up,&b.down);
    output(a);
    printf(" + ");
    output(b);
    printf(" = ");
    output(add(a,b));
    printf("\n");
    output(a);
    printf(" - ");
    output(b);
    printf(" = ");
    output(minl(a,b));
    printf("\n");
    output(a);
    printf(" * ");
    output(b);
    printf(" = ");
    output(doub(a,b));
    printf("\n");
    output(a);
    printf(" / ");
    output(b);
    printf(" = ");
    if(b.up==0)
        printf("Inf");
    else
        output(mult(a,b));
    system("pause");
    return 0;
}

宋霖轩
16 声望4 粉丝

克哈的霓虹都为我闪烁


下一篇 »
PAT A1015