2021米哈游校园招聘-提前批-编程题1-最简分式

输入一个字符串"a/b o c/d"
其中o为"+ - * /"中的一个
输出运算结果,且为最简分式*`


#include <iostream>
#include <string>
using namespace std;

//求最大公约数
int subMax(int x, int y)
{
	int z = 0;
	if (x < y)
	{
		int t = x;
		x = y;
		y = t;
	}
	//辗转相除法
	while (y != 0)
	{
		z = x % y;
		x = y;
		y = z;
	}
	return x;
}

int main()
{
	string str;
	while (getline(cin, str))
	{
		//四种运算符讨论
		int fenzi, fenzi2, fenmu, fenmu2, yueshu, yueshu2;
		switch (str[4])
		{
		case '+':
			//分母相同,不通分
			if (str[2] == str[8])
			{
				int a = (str[0] - '0') + (str[6] - '0');
				int b = str[2] - '0';
				int c = subMax(a, b);
				cout << a / c << "/" << b / c << endl;
			}
			else
			{
				//分母不同,通分
				int btemp = str[2] - '0';
				int dtemp = str[8] - '0';
				int k1 = subMax(btemp, dtemp);//最大公约数
				int k2 = btemp * dtemp / k1;//最小公倍数
				int atemp = str[0] - '0';
				int ctemp = str[6] - '0';
				int fenz = k2 / dtemp * atemp + k2 / btemp * ctemp;
				int yues = subMax(fenz, k2);
				cout << fenz / yues << "/" << k2 << endl;
			}
			break;
		case '-':
			//分母相同,不通分
			if (str[2] == str[8])
			{
				int a, c; 
				int b = str[2] - '0';
				
				if ((str[0] - '0') < (str[6] - '0'))
				{
					a = (str[6] - '0') - (str[0] - '0');
					c = subMax(a, b);
					cout << "-" << a / c << "/" << b / c << endl;
				}
				else
				{
					a = (str[0] - '0') - (str[6] - '0');
					c = subMax(a, b);
					cout << a / c << "/" << b / c << endl;
				}
			}
			else
			{
				//分母不同,通分
				int flag = 0;
				int btemp = str[2] - '0';
				int dtemp = str[8] - '0';
				int k1 = subMax(btemp, dtemp);//最大公约数
				int k2 = btemp * dtemp / k1;//最小公倍数
				int atemp = str[0] - '0';
				int ctemp = str[6] - '0';
				int fenz = k2 / btemp * atemp - k2 / dtemp * ctemp;
				if (fenz < 0)
				{
					fenz = -fenz;
					flag = 1;
				}
				int yues = subMax(fenz, k2);
				if (flag == 1)
				{
					cout << "-" << fenz / yues << "/" << k2 << endl;
				}
				else
				{
					cout << fenz / yues << "/" << k2 << endl;
				}
				
			}
			break;
		case '*':
			fenzi = (str[0] - '0') * (str[6] - '0');
			fenmu = (str[2] - '0') * (str[8] - '0');
			yueshu = subMax(fenzi, fenmu);
			cout << fenzi / yueshu << "/" << fenmu / yueshu << endl;
			break;
		case '/':
			fenzi2 = (str[0] - '0') * (str[8] - '0');
			fenmu2 = (str[2] - '0') * (str[6] - '0');
			yueshu2 = subMax(fenzi2, fenmu2);
			cout << fenzi2 / yueshu2 << "/" << fenmu2 / yueshu2 << endl;
			break;
		}
	}
	return 0;
}
posted @ 2023-03-10 20:54  Mindtechnist  阅读(30)  评论(0编辑  收藏  举报  来源