1034 有理数四则运算

1034 有理数四则运算

思路:写一个化简的函数,输入分子和分母,得到化简后的字符串。
其中需要注意的有两点:

  1. 数据类型用long long,用int会出现错误
  2. 要写一个寻找最大公因子的函数,这个函数我参考了https://www.liuchuo.net/archives/492,写的很简洁易懂
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <math.h>
#include <string>
using namespace std;

long long find_divisor(long long a, long long b)
{
	return b == 0 ? a : find_divisor(b, a % b);
}

string simply(long long a, long long b)
{
	if (b==0)
	{
		return "Inf";
	}
	if (a == 0)
	{
		return "0";
	}
	string s;
	if (a<0)
	{
		s += '(';
		s += '-';
	}
	if (a%b==0)
	{
		s += to_string( abs(a) / b);
	}
	else
	{
		//约分
		long long m = find_divisor(abs(a), b);
		a = a / m;
		b = b / m;
		if (abs(a)>b)
		{
			s += to_string( abs(a) / b);
			s += ' ';
			s += to_string( abs(a) % b);
			s += "/";
			s += to_string( b);
		}
		else
		{
			s += to_string(abs(a));
			s += "/";
			s += to_string(b);
		}
	}
	if (a < 0)
	{
		s += ')';
	}
	return s;
}

int main()
{
	long long a1, b1, a2, b2;
	char c;
	//scanf("%d%c%d %d%c%d", &a1, &c, &b1, &a2, &c, &b2);
	cin >> a1 >> c >> b1 >> a2 >> c >> b2;
	//整理成最简形式
	string s1, s2;
	s1 = simply(a1, b1);
	s2 = simply(a2, b2);
	//有理数相加
	string s3 = simply(a1 * b2 + b1 * a2, b1 * b2);
	//有理数相减
	string s4 = simply(a1 * b2 - b1 * a2, b1 * b2);
	//有理数相×
	string s5 = simply(a1 * a2, b1 * b2);
	//有理数相chu
	string s6;
	if (a2>=0)
	{
		s6 = simply(a1 * b2, b1 * a2);
	}
	else
	{
		s6 = simply(-a1 * b2, b1 * abs(a2));
	}
	printf("%s + %s = %s\n", s1.c_str(), s2.c_str(), s3.c_str());
	printf("%s - %s = %s\n", s1.c_str(), s2.c_str(), s4.c_str());
	printf("%s * %s = %s\n", s1.c_str(), s2.c_str(), s5.c_str());
	printf("%s / %s = %s\n", s1.c_str(), s2.c_str(), s6.c_str());
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值