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; } }
原文:http://www.cnblogs.com/xiongqiangcs/p/3642003.html