此题只要注意一下除法时候的负数情况就ok了,剩下的就完全模拟题意.此题中复习了一下辗转相除法,求最大公约数.
#include "iostream"
#include "string.h"
#include "string"
#include "cmath"
#include "stdio.h"
using namespace std;
int gcd(int a, int b)
{
return b==0?a:gcd(b,a%b);
}
void PrintStr(const char* str)
{
int a,b;
bool flag = false;
sscanf(str, "%d/%d", &a, &b);
if(a == 0) {
cout<< "0";
return;
}
else if (a<0) {
a = abs(a);
flag = true;
cout<<"(-";
}
int g = gcd(a, b);
a = a/g;
b = b/g;
if(a % b == 0) {
cout<<a/b;
}
else if(a>b)
cout<<a/b<<" "<<a-a/b*b<<"/"<<b;
else
cout<<a<<"/"<<b;
if(flag)
cout<<")";
}
int main ()
{
string str1, str2;
cin>>str1>>str2;
int a,b,c,d;
sscanf(str1.c_str(), "%d/%d", &a, &b);
sscanf(str2.c_str(), "%d/%d", &c, &d);
char oStr[100] = {0};
// 输出和
sprintf(oStr,"%d/%d", b*c+a*d, b*d);
PrintStr(str1.c_str());
cout<<" + ";
PrintStr(str2.c_str());
cout<<" = ";
PrintStr(oStr);
cout<<endl;
// 输出差
sprintf(oStr,"%d/%d", a*d-b*c, b*d);
PrintStr(str1.c_str());
cout<<" - ";
PrintStr(str2.c_str());
cout<<" = ";
PrintStr(oStr);
cout<<endl;
// 输出积
sprintf(oStr,"%d/%d", a*c, b*d);
PrintStr(str1.c_str());
cout<<" * ";
PrintStr(str2.c_str());
cout<<" = ";
PrintStr(oStr);
cout<<endl;
// 输出商
if(a*c<0)
sprintf(oStr,"-%d/%d", abs(a*d), abs(b*c));
else
sprintf(oStr,"%d/%d", abs(a*d), abs(b*c));
PrintStr(str1.c_str());
cout<<" / ";
PrintStr(str2.c_str());
cout<<" = ";
if(0 == c)
cout<<"Inf";
else
PrintStr(oStr);
return 0;
}