#20134: 有些測資負號要在分母,但我不知道這樣是哪種狀況會錯,計算結果是對的,不過負號在分母跟分子的問題


fdhs109_31813 (username)

學校 : 桃園市私立復旦高級中學
編號 : 103932
來源 : [140.112.25.14]
最後登入時間 :
2024-04-26 21:20:38
b538. 分數運算-2 -- 分數四則 | From: [1.34.38.39] | 發表日期 : 2019-12-05 21:15

#include<iostream>
#include<cmath>
#include<algorithm>
#include<iomanip>
#include<string>
#include<vector>
#include<sstream>
#include<cstdlib>
#define _ ios::sync_with_stdio(false); cin.tie(0);
using namespace std;

int main()
{
int a,b,c,d,x,y,g;
char k;
while(cin>>a>>b>>c>>d>>k)
{
if(k=='+')
{
x=a*d+b*c;
y=b*d;
g=__gcd(x,y);
x/=g;
y/=g;
if(x==0)
cout<<0<<endl;
else if(y==1)
cout<<x<<endl;
else if(x<0&&y<0)
cout<<-x<<"/"<<-y<<endl;
else
cout<<x<<"/"<<y<<endl;
}
else if(k=='-')
{
x=a*d-b*c;
y=b*d;
g=__gcd(x,y);
x/=g;
y/=g;
if(x==0)
cout<<0<<endl;
else if(y==1)
cout<<x<<endl;
else if(x<0&&y<0)
cout<<-x<<"/"<<-y<<endl;
else
cout<<x<<"/"<<y<<endl;
}
else if(k=='*')
{
x=a*c;
y=b*d;
g=__gcd(x,y);
x/=g;
y/=g;
if(x==0)
cout<<0<<endl;
else if(y==1)
cout<<x<<endl;
else if(x<0&&y<0)
cout<<-x<<"/"<<-y<<endl;
else
cout<<x<<"/"<<y<<endl;
}
else if(k=='/')
{
x=a*d;
y=b*c;
g=__gcd(x,y);
x/=g;
y/=g;
if(x==0)
cout<<0<<endl;
else if(y==1)
cout<<x<<endl;
else if(x<0&&y<0)
cout<<-x<<"/"<<-y<<endl;
else
cout<<x<<"/"<<y<<endl;
}
}
}

 
ZeroJudge Forum