1034 有理数四则运算
思路:写一个化简的函数,输入分子和分母,得到化简后的字符串。
其中需要注意的有两点:
- 数据类型用long long,用int会出现错误
- 要写一个寻找最大公因子的函数,这个函数我参考了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;
}