1336 - 分数计算
题目描述
从键盘读入一个分数算式,为 22 个分数做加法或者减法,请输出分数算式的结果,结果也用分数表达,且约分到最简形式。(请注意:做减法可能得到负的分数,如果是负数要输出负号 -
,如 1/15-4/15
结果为 -1/5
)(5.1.76)
输入
分数表达式;分数表达式中,每个分数的分子和分母都是正整数(不超过 10001000 ),两个分数中的运算符,可能是加号,也可能是减号,且分数表达式不含空格。
输出
分数表达式计算的结果。
样例
输入
复制
1/12+5/12
输出
复制
1/2
输入
复制
1/2+1/2
输出
复制
1
输入
复制
1/2-1/2
输出
复制
0
说明
注意考虑特殊情况,如:1/2+1/2=1
,1/2-1/2=0
,这些情况下结果不需要表现为分数形式。
代码:
注意!本程序用了stoi函数,如用Dev-C++,请改设置(可以私信我!)!
#include<bits/stdc++.h>
using namespace std;
string s,s1,s2,fz1,fm1,fz2,fm2;
int a1,b1,a2,b2;
int p,t;
int r1,r2;
int gys(int a,int b){
int temp;
while(a%b!=0){
temp=a%b;
a=b;
b=temp;
}
return b;
}
int main(){
cin>>s;
p=s.find("+");
if(p==-1){
p=s.find("-");
}
s1=s.substr(0,p);
s2=s.substr(p+1);
fz1=s1.substr(0,s1.find("/"));
fm1=s1.substr(s1.find("/")+1);
fz2=s2.substr(0,s2.find("/"));
fm2=s2.substr(s2.find("/")+1);
a1=stoi(fz1);
b1=stoi(fm1);
a2=stoi(fz2);
b2=stoi(fm2);
r2=b1*b2;
if(s.find("+")!=-1){
r1=a1*b2+a2*b1;
}else{
r1=a1*b2-a2*b1;
if(r1<0){
cout<<"-";
r1=r1*-1;
}
}
t=gys(r1,r2);
if(r1%r2==0){
cout<<r1/r2;
}else{
cout<<r1/t<<"/"<<r2/t;
}
return 0;
}