一道模拟,按照题目要求手模就行,很容易懂
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int a[101],b[101];//a代表分子,b代表分母
int ans;
long long p=1,t,gp;
char o;
string s;
stack<char>q;
bool flag,chck;
int f=1,num;
int main() {
cin>>s;//字符串形式读入
for(int i=s.size()-1; i>=0; i--)
q.push(s[i]);//倒序压入栈,因为栈是先进先出,你也可以把它正序压入队列
while(!q.empty()) {
o=q.top();
if(o=='+') f=1,flag=0;//处理加号
if(o=='-') f=-1,flag=0;//处理减号
if(o=='/') flag=1,a[num]*=f;//分子读完,处理正负
if(o<='9'&&o>='0') {
if(flag==0)
{
if(chck==0)//一个新分子,num加一
num++,chck=1;
a[num]=a[num]*10+o-'0';//将字符转换为整数,类似于读入优化
}
else b[num]=b[num]*10+o-'0',chck=0;//处理分母,chck清零,准备读取下一个分子
}
q.pop();
}
for(int i=1;i<=num;i++)
p*=b[i];//求分母的乘积,通分
for(int i=1;i<=num;i++)
{
t+=a[i]*(p/b[i]);//计算分子的和,乘以p/b[i]是因为分母已通分
}
if(t<0)
{
putchar('-');//将分子转换成整数,因为gcd不支持负数最大公因数(~~本蒟蒻不清楚~~)
t=-t;
}
if(t%p==0) //如果t%p==0说明分数可化为整数,输出t/p
{
cout<<t/p;
return 0;
}
gp=__gcd(t,p);//STL自带求最大公因数
t/=gp;
p/=gp;//约分
printf("%lld",t);
printf("/");
printf("%lld",p);
return 0;//华丽的结束
}