分数加减法

来源:互联网 发布:applewatch怎么解锁mac 编辑:程序博客网 时间:2024/04/29 19:18

这题的关键是列出各种计算结果的情况:结果为0,结果为1,结果为整数。

我就是忘了结果为整数的情况导致一直AC不了

#include <iostream>#include <cstring>#include <cmath>#include <cstdlib>const int MAX = 10;using namespace std;int getGCD(int a, int b){if(a<b){int t = a;a = b;b = t;}if(b==0)return a;else return getGCD(b, a%b);}int main(){char ch[MAX];while(cin.getline(ch,10)){int a0, b0, a1, b1;char o;a0 = atoi(ch);char* p = strchr(ch, '/');b0 = atoi(++p);while(isdigit(*(++p)));o = *p;a1 = atoi(++p);p = strchr(p, '/');b1 = atoi(++p);int n, m;if(o=='+'){n = a0*b1+a1*b0;m = b0*b1;}else if(o=='-'){n = a0*b1-a1*b0;m = b0*b1;}if(n!=0){if(n!=m){int GCD = getGCD(fabs((double)m), fabs((double)n));n/=GCD;m/=GCD;if(m!=1){if(n>0&&m>0||n<0&&m<0)cout<<n<<'/'<<m<<endl;elsecout<<'-'<<fabs((double)n)<<'/'<<fabs((double)m)<<endl;}else cout<<n<<endl;}elsecout<<1<<endl;}else cout<<0<<endl;}return 0;}


0 0
原创粉丝点击