这道题只要知道最大公约数和最小公倍数的求法就可以做得出来,但是要考虑的输出细节比较繁琐,代码写的很丑啦,不过总算是全部case通过了。
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
struct rational{
int numerator;
int denominator;
};
int gcd(int a,int b)
{
if (b==0) {
return a;
}
else
return gcd(b,a%b);
}
int lcm(int a,int b){
return a*b/gcd(a, b);
}
rational add(rational sum,rational next){
int l=lcm(sum.denominator, next.denominator);
//开始通分并相加
sum.numerator=(l/sum.denominator)*sum.numerator;
next.numerator=(l/next.denominator)*next.numerator;
sum.numerator+=next.numerator;
sum.denominator=l;
//对结果进行约分
int g=gcd(sum.denominator, sum.numerator);
sum.numerator/=g;
sum.denominator/=g;
return sum;
}
void output(rational sum){
int integ;
if (sum.numerator==0) {
printf("0\n");
return;
}
if (sum.numerator<0) {
printf("-");
sum.numerator*=-1;
}
integ=sum.numerator/sum.denominator;
if (integ!=0) {
printf("%d",integ);
sum.numerator=sum.numerator-integ*sum.denominator;
}
if (integ!=0&&sum.numerator!=0) {
printf(" ");
}
if (sum.numerator!=0) {
printf("%d/%d\n",sum.numerator,sum.denominator);
}
else
printf("\n");
}
int main(){
int n;
rational sum,next;
// freopen("/Users/pantingting/Documents/code/data/input", "r", stdin);
scanf("%d",&n);
sum.denominator=1;
sum.numerator=0;
for (int i=0; i<n; i++) {
scanf("%d/%d",&next.numerator,&next.denominator);
sum=add(sum, next);
}
output(sum);
return 0;
}