String good question! Other explanationsReadability is not highI use the most simple ideas to explain it again
analysis:
- If you read a string into a word processing from the numerator and denominator will be very troublesome, and when read with
scanf("%d/%d",&a,&b)
can easily deal with the sign of the words Common denominator: a
a*b=lcm(a,b)*gcd(a,b)
, toolcm(a,b)=a * b/gcd(a,b)
This question pit
- 1:00 denominator is required special sentence
- Results into the most simple integer ratio: we can count on every time when they are taken over __gcd (a, b) <--- This is a library function, hands-free play again gcd,
Although much time did not save Most pit point: When the denominator is negative, eg
2/-3
become-2/3
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,a,b) for(ll i=a;i<=b;++i)
#define dwn(i,a,b) for(ll i=a;i>=b;--i)
template <typename T> inline void rd(T &x){
x=0;char c=getchar();int f=0;
while(!isdigit(c)){f|=c=='-';c=getchar();}
while(isdigit(c)){x=(x<<1)+(x<<3)+(c^48);c=getchar();}
x=f?-x:x;
}
#define mem(a,b) memset(a,b,sizeof(a))
int a,b,c,d;
int ans1;//分子
int ans2;//分母
int main(){
scanf("%d/%d",&a,&b);
while(scanf("%d/%d",&c,&d)!=EOF){
int gcd=__gcd(b,d);
int lcm=b*d/gcd;
ans2=lcm;//当前分母
ans1=a*(lcm/b)+c*(lcm/d);//当前分子,请读者自主模拟一下
a=ans1/(__gcd(ans1,ans2));//下一次计算时,a和b代表的是上一次计算的分子分母,顺便约个分
b=ans2/(__gcd(ans1,ans2));
}
ans1=a;//最后一次处理后a就是ans1,这里赋值的原因是a与b约过一次分了
ans2=b;//最后一次处理后b就是ans2
if(ans2<0){//处理 2/-3 -> -2/3的情况
ans1=-ans1;
ans2=-ans2;
}
if(ans2==1)printf("%d\n",ans1);//处理分母为1的情况
else printf("%d/%d\n",ans1,ans2);
return 0;
}