PAT L1-009. N个数求和

L1-009. N个数求和

分数求和…真的是细节丰富的模拟题
注意要点:
1.负数的处理,尤其是连加到一半,sum=0的时候,要把sum赋值为0/1继续连加
2.输入的是long long,主要不要爆int,每次连加的时候要约分

#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cmath>
#define f first
#define s second
using namespace std;
typedef long long LL;
typedef pair<LL,LL> P;
P num[120];

LL gcd(LL a,LL b)
{
  if(a % b == 0) return b;
  else return gcd(b,a%b);
}

bool divide(P &p)  //约分函数,顺便判断分子是否为0
{
  if(p.f == 0)  return true;
  LL tmp = gcd(abs(p.f),abs(p.s));
  p.f /= tmp;
  p.s /= tmp;
  return false;
}

int main()
{
  int n;
  cin >> n;
  getchar();
  for(int i=0;i<n;i++)
  {
    scanf("%lld/%lld",&num[i].f,&num[i].s);
    divide(num[i]);
  }
  for(int i=1;i<n;i++)
  {
    P tmp;
    tmp.s = num[0].s * num[i].s;
    tmp.f = num[0].f * num[i].s + num[i].f * num[0].s;
    num[0].f = tmp.f;
    num[0].s = tmp.s;
    bool flag = divide(num[0]);
    if(flag)
    {
      if(i == n-1)  break;
      else
      {
        num[0].s = 1;
      }
    }
  }
  if(num[0].f == 0) cout << 0 << endl;
  else
  {
    int pre = num[0].f / num[0].s;
    if(pre == 0)  cout << num[0].f << '/' << num[0].s << endl;
    else
    {
      cout << pre;
      num[0].f = num[0].f % num[0].s;
      if(num[0].f == 0) cout << endl;
      else cout << " " << num[0].f << '/' << num[0].s << endl;
    }
  }
}
... ... ...