PAT (Basic Level) 1034 有理数四则运算(模拟)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_45458915/article/details/102697728

题目链接:点击查看

题目大意:模拟有理数的四则运算

题目分析:这个题真的考验代码实现能力,我模拟了好一会,终于是把样例过掉了,然后交了一发WA了两个测试点,一下子想起来如果直接乘的话会爆int,全部改成longlong后又过了一个测试点,最后那个测试点我也不知道为什么,对于每个分数必须先化简才能继续操作,不然可能会在某个地方爆掉longlong吧,原理不明

写这种题的时候一定要保证思路清晰,不能分神,不然一会就不知道自己在写什么东西了,还有要记得写注释,这个题为了尽可能理清思路我把注释写的差不多还算可以,然后就是巧用stl(stl重度依赖症患者表示没救了),还有就是C++11里很好用的to_string()函数,可以把好多数据类型直接转换为string类,然后用加号就能连接了,直接上代码了:

#include<iostream>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<cmath>
#include<cctype>
#include<stack>
#include<queue>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<sstream> 
#include<unordered_map>
using namespace std;

typedef long long LL;

const int inf=0x3f3f3f3f;

const int N=1e5+100;

string change(LL a,LL b)
{
	if(a==0)//特判0
		return "0";
	LL gcd=__gcd(abs(a),abs(b));//先化简
	a/=gcd;
	b/=gcd;
	if(a*b<0)//将负号归到分子上
	{
		a=-abs(a);
		b=abs(b);
	}
	else
	{
		a=abs(a);
		b=abs(b);
	}
	string ans;
	LL k=a/b;
	if(k)//假分数 
	{
		if(b==1)//整数 
		{
			if(a>0)//正数
			{
				ans+=to_string(k);
			}
			else//负数
			{
				ans+="(-";
				ans+=to_string(-k);
				ans+=")";
			}
		}
		else if(a>0)//正数
		{
			ans+=to_string(k);
			ans+=" ";
			ans+=to_string(a%b);
			ans+="/";
			ans+=to_string(b);
		}
		else//负数 
		{
			ans+="(-";
			ans+=to_string(-k);
			ans+=" ";
			ans+=to_string(-(a%b));
			ans+="/";
			ans+=to_string(b);
			ans+=")";
		} 
	}
	else//真分数 
	{
		if(a>0)//正数 
		{
			ans+=to_string(a);
			ans+="/";
			ans+=to_string(b);
		}
		else//负数 
		{
			ans+="(-";
			ans+=to_string(-(a%b));
			ans+="/";
			ans+=to_string(b);
			ans+=")";
		}
	}
	return ans;
}

string plu(LL a,LL b,LL c,LL d)//加
{
	return change(a*d+c*b,b*d);
}

string sub(LL a,LL b,LL c,LL d)//减
{
	return change(a*d-c*b,b*d);
}

string mul(LL a,LL b,LL c,LL d)//乘
{
	return change(a*c,b*d);
}

string div(LL a,LL b,LL c,LL d)//除
{
	return change(a*d,b*c);
}

int main()
{
	LL a,b,c,d;
	scanf("%lld/%lld %lld/%lld",&a,&b,&c,&d);
	string ans1=change(a,b);
	string ans2=change(c,d);
	printf("%s + %s = %s\n",ans1.c_str(),ans2.c_str(),plu(a,b,c,d).c_str());
	printf("%s - %s = %s\n",ans1.c_str(),ans2.c_str(),sub(a,b,c,d).c_str());
	printf("%s * %s = %s\n",ans1.c_str(),ans2.c_str(),mul(a,b,c,d).c_str());
	if(c)//除法特判
		printf("%s / %s = %s\n",ans1.c_str(),ans2.c_str(),div(a,b,c,d).c_str());
	else
		printf("%s / %s = %s\n",ans1.c_str(),ans2.c_str(),"Inf");
	
	
	
	
	
	
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/102697728
今日推荐