题意:
输入一个正整数N(<=100),接着输入N个由两个整数和一个/组成的分数。输出N个分数的和。
代码:
#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
int a[107],b[107];
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin>>n;
for(int i=1;i<=n;++i){
cin>>a[i];
cin.ignore();
cin>>b[i];
int t=max(1,__gcd(a[i],b[i]));
a[i]/=t;
b[i]/=t;
}
int ans=0;
for(int i=2;i<=n;++i){
int tamp=b[i-1]*b[i];
int sum=a[i]*b[i-1]+a[i-1]*b[i];
int t=__gcd(tamp,sum);
tamp/=t;
sum/=t;
ans+=sum/tamp;
sum%=tamp;
a[i]=sum;
b[i]=tamp;
}
if(ans&&a[n])
cout<<ans<<" "<<a[n]<<"/"<<b[n];
else if(ans)
cout<<ans;
else if(a[n])
cout<<a[n]<<"/"<<b[n];
else
cout<<0;
return 0;
}
原文地址:https://www.cnblogs.com/ldudxy/p/11841776.html