版权声明:个人学习笔记记录 https://blog.csdn.net/Ratina/article/details/84578634
本题要求编写程序,计算 2 个有理数的和、差、积、商。
输入格式:
输入在一行中按照 a1/b1 a2/b2 的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为 0。
输出格式:
分别在 4 行中按照 有理数1 运算符 有理数2 = 结果 的格式顺序输出 2 个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式 k a/b,其中 k 是整数部分,a/b 是最简分数部分;若为负数,则须加括号;若除法分母为 0,则输出 Inf。题目保证正确的输出中没有超过整型范围的整数。
输入样例 1:
2/3 -4/2
输出样例 1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
输入样例 2:
5/3 0/6
输出样例 2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf
模拟题,注意细节,再就是 " 题目保证正确的输出中没有超过整型范围的整数 ”,但是结果可能会超过int,所以要用long long。
具体看代码。
#include<iostream>
#include<cstdio>
using namespace std;
struct node
{
long long a; //分子
long long b; //分母
};
node simplfy(node temp) //化简
{
long long m=temp.a,n=temp.b,k;
while (n!= 0) //辗转相除法求GCD
{
k=m%n;
m=n;
n=k;
}
temp.a/=m;
temp.b/=m;
return temp;
}
node read() //读入
{
node temp;
cin>>temp.a;
getchar();
cin>>temp.b;
return temp;
}
void output(node x) //输出
{
x=simplfy(x); //先化简
if(x.b<0) //保证负号在分子上 (如果分子、分母同为负,这个操作还能将负号约掉)
{
x.a=-x.a;
x.b=-x.b;
}
if(x.a==0) //特判分子为0的情况
cout<<"0";
else
{
bool negative=false;
if(x.a<0) //如果为负数
negative=true;
if(negative)
{
cout<<"(-";
x.a=-x.a;
}
if(x.a/x.b!=0)
cout<<x.a/x.b;
if(x.a%x.b!=0)
{
if(x.a/x.b!=0) //注意:如果无整数部分,是不需要中间加空格的
cout<<" ";
cout<<x.a%x.b<<"/"<<x.b;
}
if(negative)
cout<<")";
}
}
node Plus(node f,node s) //相加
{
node temp;
temp.b=f.b*s.b;
temp.a=f.a*s.b+s.a*f.b;
return temp;
}
node Minus(node f,node s) //相减
{
node temp;
temp.b=f.b*s.b;
temp.a=f.a*s.b-s.a*f.b;
return temp;
}
node Multiply(node f,node s) //相乘
{
node temp;
temp.a=f.a*s.a;
temp.b=f.b*s.b;
return temp;
}
node Divide(node f,node s) //相除
{
node temp;
temp.a=f.a*s.b;
temp.b=s.a*f.b;
return temp;
}
int main()
{
node first,second,ans;
first=read();
second=read();
//相加
ans=Plus(first,second);
output(first);
cout<<" + ";
output(second);
cout<<" = ";
output(ans);
cout<<endl;
//相减
ans=Minus(first,second);
output(first);
cout<<" - ";
output(second);
cout<<" = ";
output(ans);
cout<<endl;
//相乘
ans=Multiply(first,second);
output(first);
cout<<" * ";
output(second);
cout<<" = ";
output(ans);
cout<<endl;
//相除
ans=Divide(first,second);
output(first);
cout<<" / ";
output(second);
cout<<" = ";
if(second.a==0) //特判除数为0的情况
cout<<"Inf";
else
output(ans);
cout<<endl;
return 0;
}