#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;cin>>n;
long long a[1001],b[1001];char c;long long zhengshu=0,fenzi;
for(int i=1;i<=n;i++)
{
cin>>a[i]>>c>>b[i];
}
if(n==1)
{
if(a[1]==0)cout<<"0";
else{
long long n=__gcd(a[1],b[1]);
a[1]/=n;
b[1]/=n;
zhengshu=a[1]/b[1];
fenzi=a[1]-(zhengshu*b[1]);
if(zhengshu&&fenzi)cout<<zhengshu<<" "<<fenzi<<"/"<<b[1];
else if(zhengshu==0&&fenzi)cout<<fenzi<<"/"<<b[1];
else if(fenzi==0&&zhengshu)cout<<zhengshu;
else if(fenzi==0&&zhengshu==0)cout<<"0";
}
}
else {
for(int i=1;i<n;i++)
{
long long gcd=__gcd(b[i],b[i+1]);
long long yue=b[i]*b[i+1]/gcd;
a[i+1]=yue/b[i]*a[i]+yue/b[i+1]*a[i+1];b[i+1]=yue;
if(i==n-1)
{
zhengshu=a[i+1]/b[i+1];fenzi=a[i+1]%b[i+1];
long long n=__gcd(fenzi,b[i+1]);
fenzi/=n;
b[i+1]/=n;
if(zhengshu&&fenzi)
{
if(b[i+1]<0)cout<<zhengshu<<" "<<-fenzi<<"/"<<abs(b[i+1]);
else
cout<<zhengshu<<" "<<fenzi<<"/"<<b[i+1];
}
else if(zhengshu==0&&fenzi)
{
if(b[i+1]<0)cout<<-fenzi<<"/"<<abs(b[i+1]);
else
cout<<fenzi<<"/"<<b[i+1];
}
else if(fenzi==0&&zhengshu)cout<<zhengshu;
else if(fenzi==0&&zhengshu==0)cout<<"0";
}
}
}
}
题解:
最大公约数可以直接调用__gcd(int a,int b);
一个小小知识点:两个数的乘积等于这两个数的最小公倍数乘以最大公约数
用这个知识点可以求出两个数的最小公倍数