http://acm.nyist.net/JudgeOnline/problem.php?pid=111
简单模拟:
#include <iostream> #include <string> #include <cstring> using namespace std; int gcd(int a,int b) { if(a<b)return gcd(b,a); if(b==0)return a; return gcd(b,a%b); } int lcm(int a,int b) { return a*b/gcd(a,b); } int main() { string s; int fz1,fm1,fz2,fm2; char ch; while(cin>>s) { fz1=s[0]-'0'; fm1=s[2]-'0'; fz2=s[4]-'0'; fm2=s[6]-'0'; ch=s[3]; int fm=lcm(fm1,fm2); fz1=fz1*(fm/fm1); fz2=fz2*(fm/fm2); int fz; if(ch=='+'){ fz=fz1+fz2; if(fz%fm==0){cout<<fz/fm<<endl;continue;}// 2/1或者4/2这种情况应该直接输出 int tmp=gcd(fz,fm); fz=fz/tmp; fm=fm/tmp; if(fz==fm)cout<<1<<endl; else cout<<fz<<"/"<<fm<<endl; } else { fz=fz1-fz2; if(fz%fm==0){cout<<fz/fm<<endl;continue;} if(fz==0)cout<<0<<endl; else { int tmp; if(fz<0) tmp=gcd(-fz,fm); else tmp=gcd(fz,fm); fz=fz/tmp; fm=fm/tmp; if(fz==fm)cout<<1<<endl; // 1/1这种情况应该输出1 else cout<<fz<<"/"<<fm<<endl; } } } return 0; }