题目描述
本题要求编写程序,计算2个有理数的和、差、积、商。
输入描述:
输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分 母不为0。
输出描述:
分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的 最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”。题目保证正确的输出中 没有超过整型范围的整数。
输入例子:
5/3 0/6
输出例子:
1 2/3 + 0 = 1 2/3 1 2/3 - 0 = 1 2/3 1 2/3 * 0 = 0 1 2/3 / 0 = Inf
不得不说,此题表面要求很简单,实际上有各种恶心的格式要求,修改多次。。。负数加括号、整数为零不输出、整数为负输出后分子输出为正,若分子分母整除则只输出整数。
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <ctime>
#include<iostream>
using namespace std;
struct fenshu
{
int z;
int a;
int b;
};
int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b,a%b);
}
void hj1(fenshu &fs)
{
//cout<<"false"<<endl;
if(fs.a==0)
fs.b=1;
else
{
int d=gcd(abs(fs.a),abs(fs.b));
fs.a/=d;
fs.b/=d;
}
if(fs.b<0)
{
fs.a=-fs.a;
fs.b=-fs.b;
}
//cout<<fs.a<<" "<<fs.b<<endl;
}
void hj2(fenshu &fs)
{
fs.z=fs.a/fs.b;
if(fs.a<0)
fs.a=-1*(abs(fs.a)%fs.b);
else fs.a=fs.a%fs.b;
}
void cout1(fenshu fs)
{
if(fs.a==0&&fs.z==0)
cout<<"0";
else if(fs.a<0)
{
cout<<"(";
if(fs.z==0);
else if(fs.z<0)
{
cout<<fs.z<<" ";
fs.a=abs(fs.a);
}
cout<<fs.a;
cout<<"/";//整数和结构体不能同时输出????
cout<<fs.b;
cout<<")";
}
else if(fs.a>0)
{
if(fs.z==0);
else cout<<fs.z<<" ";
cout<<fs.a;
cout<<"/";//整数和结构体不能同时输出????
cout<<fs.b;
}
else if(fs.a==0&&fs.z!=0)
{
if(fs.z<0)
{
cout<<"(";
cout<<fs.z<<")";
}
else
cout<<fs.z;
}
}
int main()
{
int i,j,k,m,n;
fenshu fs1,fs2,fs11,fs22;
char c;
cin>>fs1.a>>c>>fs1.b;
cin>>fs2.a>>c>>fs2.b;
fs11=fs1;
fs22=fs2;
fenshu fs3,fs4,fs5,fs6;
fs3.a=fs1.a*fs2.b+fs2.a*fs1.b;
fs3.b=fs1.b*fs2.b;
hj1(fs3);
hj2(fs3);
fs4.a=fs1.a*fs2.b-fs2.a*fs1.b;
fs4.b=fs1.b*fs2.b;
hj1(fs4);
hj2(fs4);
fs5.a=fs1.a*fs2.a;
fs5.b=fs1.b*fs2.b;
hj1(fs5);
hj2(fs5);
hj1(fs22);
hj1(fs11);
hj2(fs22);
hj2(fs11);
cout1(fs11);cout<<" "<<"+"<<" ";cout1(fs22);cout<<" "<<"="<<" ";cout1(fs3);cout<<endl;
cout1(fs11);cout<<" "<<"-"<<" ";cout1(fs22);cout<<" "<<"="<<" ";cout1(fs4);cout<<endl;
cout1(fs11);cout<<" "<<"*"<<" ";cout1(fs22);cout<<" "<<"="<<" ";cout1(fs5);cout<<endl;
if(fs2.a!=0)
{
fs6.a=fs2.b*fs1.a;
fs6.b=fs1.b*fs2.a;
hj1(fs6);
hj2(fs6);
cout1(fs11);cout<<" "<<"/"<<" ";cout1(fs22);cout<<" "<<"="<<" ";cout1(fs6);cout<<endl;
}
else{
cout1(fs11);cout<<" "<<"/"<<" ";cout<<"0";cout<<" "<<"="<<" ";cout<<"Inf";cout<<endl;
}
}