ACM 分數加減法

OpenSoucre發表於2014-04-03

分數加減法

時間限制:3000 ms  |  記憶體限制:65535 KB
難度:2
 
描述
編寫一個C程式,實現兩個分數的加減法
 
輸入
輸入包含多行資料 
每行資料是一個字串,格式是"a/boc/d"。 
其中a, b, c, d是一個0-9的整數。o是運算子"+"或者"-"。 

資料以EOF結束 
輸入資料保證合法
輸出
對於輸入資料的每一行輸出兩個分數的運算結果。 
注意結果應符合書寫習慣,沒有多餘的符號、分子、分母,並且化簡至最簡分數
樣例輸入
1/8+3/8
1/4-1/2
1/3-1/3
樣例輸出
1/2
-1/4
0

特別注意2/1+4/1這種整除的情況
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int gcd(int a,int b){
    if(a < 0) a = -a;
    if(a < b) swap(a,b);
    while(b){
        int t = b;
        b = a%b;
        a = t;
    }
    return a;
}

int main(){
    string str;
    while(cin>>str){
        int a = str[0]-'0', b = str[2]-'0', c=str[4]-'0', d=str[6]-'0';
        int numerator = a*d+c*b,denominator=d*b;
        if(str[3] == '-') numerator = a*d-c*b;
        int v = gcd(numerator,denominator);
        numerator /=v;
        denominator /=v;
        if(numerator == 0) cout<<0<<endl;
        else if(denominator == 1) cout<<numerator<<endl;
        else cout<<numerator<<"/"<<denominator<<endl;
    }
}

 

相關文章