本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数分子/分母的形式给出的,你输出的和也必须是有理数的形式。
输入格式:
输入第一行给出一个正整数N(≤100)。随后一行按格式a1/b1 a2/b2 …给出N个有理数。题目保证所有分子和分母都在长整型范围内。另外,负数的符号一定出现在分子前面。
输出格式:
输出上述数字和的最简形式 —— 即将结果写成整数部分 分数部分,其中分数部分写成分子/分母,要求分子小于分母,且它们没有公因子。如果结果的整数部分为0,则只输出分数部分。
输入样例1:
5
2/5 4/15 1/30 -2/60 8/3
输出样例1:
3 1/3
输入样例2:
2
4/3 2/3
输出样例2:
2
输入样例3:
3
1/3 -1/6 1/8
输出样例3:
7/24
运用自顶向下方法 C语言描述
#include<stdio.h>
typedef struct{
int p;
int q;
} rationalnumT;
int ReadNRatinalNumber(rationalnumT rational[],int num);
int GCD(int x,int y);
void ReductionFraction(rationalnumT *r);
rationalnumT RationalAddition(rationalnumT r1, rationalnumT r2);
rationalnumT AddNRational(rationalnumT rational[],int num);
void PrintMixedNumber(rationalnumT r);
main()
{
int num;
rationalnumT rat[100],sum;
scanf("%d",&num);
ReadNRatinalNumber(rat,num);
sum=AddNRational(rat,num);
PrintMixedNumber(sum);
}
int ReadNRatinalNumber(rationalnumT rational[],int num)
{
int i;
for(i=0;i<num;i++){
scanf("%d/%d",&rational[i].p,&rational[i].q);
}
return 0;
}
rationalnumT RationalAddition(rationalnumT r1, rationalnumT r2)
{
rationalnumT r;
int d;
ReductionFraction(&r1);
ReductionFraction(&r2);
d=GCD(r1.q,r2.q);
r.q=r1.q /d* r2.q ;
r.p=r2.q / d * r1.p+r1.q / d*r2.p;
return (r);
}
void ReductionFraction(rationalnumT *r)
{
int d;
d=GCD(r->p,r->q);
r->p/=d;
r->q/=d;
}
rationalnumT AddNRational(rationalnumT rational[],int num)
{
int i;
rationalnumT sum={0,1};
for(i=0;i<num;i++){
sum=RationalAddition(sum,rational[i]);
}
return sum;
}
void PrintMixedNumber(rationalnumT r)
{
int quotient,remainder;
quotient=r.p/r.q;
remainder=r.p-quotient*r.q;
if(quotient&&remainder){
printf("%d %d/%d",quotient,remainder,r.q);
}else if(remainder==0){
printf("%d",quotient);
}else{
printf("%d/%d",remainder,r.q);
}
}
int GCD(int x,int y)
{
int r;
x=x>0?x:-x;
y=y>0?y:-y;
if(y==0) return x;
while(1){
r=x%y;
if(r==0) break;
x=y;
y=r;
}
return (y);
}