分数运算,不难,但输出格式十分复杂,同时包含最大公约数和最小公倍数的考察。
有一个小知识点,itoa可以将char* 转换成int ,ltoa可以将char* 转换成long ing,但这题的long long int好像没有对应的方法。
可以改成sprintf(char* ans, "%lld", int x);
#include<stdio.h>
#include<string>
using namespace std;
long long GCD(long long a, long long b)
{
while (b != 0)
{
long long t = a%b;
a = b;
b = t;
}
return a;
}
string convert(long long a, long long b, long long i, bool sign)
{
a = a%b;
string res = "";
res += sign ? "" : "(-";
char integer[30], numerator[30], denominator[30];
sprintf(integer, "%lld", i);
sprintf(denominator, "%lld", b);
sprintf(numerator, "%lld", a);
if (a == 0)
{
res += string(integer);
}
else if (i == 0)
{
res += string(numerator) + "/" + string(denominator);
}
else
{
res += string(integer) + " " + string(numerator) + "/" + string(denominator);
}
res += sign ? "" : ")";
return res;
}
void add(long long a1, long long b1, long long s1,
long long a2, long long b2, long long s2, bool isAdd)
{
string ans;
long long a3, b3, s3 = 1, gcd;
b3 = b1*b2 / GCD(b1, b2);
a3 = s1*a1*b3 / b1 + (isAdd ? (s2*a2*b3 / b2) : (-s2*a2*b3 / b2));
if (a3 < 0)
{
s3 = -1;
a3 = -a3;
}
gcd = GCD(a3, b3);
a3 /= gcd;
b3 /= gcd;
ans = convert(a1, b1, a1 / b1, (s1 == -1) ? false : true) + (isAdd ? " + " : " - ") +
convert(a2, b2, a2 / b2, (s2 == -1) ? false : true) + " = " +
convert(a3, b3, a3 / b3, (s3 == -1) ? false : true);
printf("%s\n", ans.c_str());
}
void multi(long long a1, long long b1, long long s1,
long long a2, long long b2, long long s2, bool isMulti)
{
string ans;
long long a3, b3, s3 = 1, gcd;
if (isMulti)
{
b3 = b1*b2;
a3 = s1*a1*s2*a2;
}
else
{
b3 = b1*a2;
a3 = a1*b2*s1*s2;
}
if (a3 < 0)
{
s3 = -1;
a3 = -a3;
}
if (b3 != 0)
{
gcd = GCD(a3, b3);
a3 /= gcd;
b3 /= gcd;
ans = convert(a1, b1, a1 / b1, (s1 == -1) ? false : true) + (isMulti ? " * " : " / ") +
convert(a2, b2, a2 / b2, (s2 == -1) ? false : true) + " = " +
convert(a3, b3, a3 / b3, (s3 == -1) ? false : true);
}
else
{
ans = convert(a1, b1, a1 / b1, (s1 == -1) ? false : true) + (isMulti ? " * " : " / ") +
convert(a2, b2, a2 / b2, (s2 == -1) ? false : true) + " = Inf";
}
printf("%s\n", ans.c_str());
}
int main()
{
string ans;
long long a1, b1, s1 = 1, a2, b2, s2 = 1, a3, b3, s3 = 1;
scanf("%lld/%lld %lld/%lld", &a1, &b1, &a2, &b2);
if (a1 < 0)
{
s1 = -1;
a1 = -a1;
}
if (a2 < 0)
{
s2 = -1;
a2 = -a2;
}
long long gcd, lcm;
gcd = GCD(a1, b1);
a1 /= gcd;
b1 /= gcd;
gcd = GCD(a2, b2);
a2 /= gcd;
b2 /= gcd;
add(a1, b1, s1, a2, b2, s2, true);
add(a1, b1, s1, a2, b2, s2, false);
multi(a1, b1, s1, a2, b2, s2, true);
multi(a1, b1, s1, a2, b2, s2, false);
return 0;
}