当前位置: 代码迷 >> 综合 >> C++ - PAT - 1034. 有理数四则运算(20)
  详细解决方案

C++ - PAT - 1034. 有理数四则运算(20)

热度:91   发布时间:2023-10-09 18:27:26.0

本题要求编写程序,计算2个有理数的和、差、积、商。

输入格式:

输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分母不为0。

输出格式:

分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”。题目保证正确的输出中没有超过整型范围的整数。

输入样例1:
2/3 -4/2
输出样例1:
2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)
输入样例2:
5/3 0/6
输出样例2:
1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf


#include<cstdio>
#include<iostream>using namespace std;
long long int a,b,c,d;
int main(){void add();void sub();void multi();void div();// a/b  c/dscanf("%lld/%lld %lld/%lld",&a,&b,&c,&d);add();sub();multi();div();return 0;
}
//最大公约数 
long long int Gcd(long long int a,long long int b){return b==0 ? a : Gcd(b, a%b);
}
//输出最简分数 
//1.最大公约数是1 
//2.最大公约数是分母
//3.最大公约数是分子 
//4.最大公约数是某个数 
// 
//1.分子是0  .
//2.分母是0  .void func(long long int a,long long int b){int flag1 = 0;int flag2 = 0;int flag = 0;if(a<0){flag1 = 1;a = -a;}if(b<0){flag2 = 1;b = -b;}if(flag1==1&&flag2==1){flag = 0;}else if(flag1==0&&flag2==0){flag = 0;}else{flag = 1;}if(a==0){cout<<0;return ;}if(b==0){cout<<"Inf";return ;}if(a%b==0){if(flag){cout<<"(-"<<a/b<<")";return ;}else{cout<<a/b;return ;}}if(a<b){long long int n = a/Gcd(a,b);long long int m = b/Gcd(a,b);if(flag){cout<<"(-"<<n<<"/"<<m<<")";return ;}else{cout<<n<<"/"<<m;return ;}}if(a>b){long long int zs = a/b;long long int n = a -(b*(a/b));long long int m = b;if(flag){cout<<"(-"<<zs<<" ";cout<<n/Gcd(n,m)<<"/"<<m/Gcd(n,m)<<")";return ;}else{cout<<zs<<" ";cout<<n/Gcd(n,m)<<"/"<<m/Gcd(n,m);return ;}}}// "+"
void add(){long long int m ,n;n = a*d+b*c;m = b*d;func(a,b);cout<<" + ";func(c,d);cout<<" = ";func(n,m);cout<<endl;}
// "-"
void sub(){long long int m ,n;n = a*d-b*c;m = b*d;func(a,b);cout<<" - ";func(c,d);cout<<" = ";func(n,m);cout<<endl;
}
// "*"
void multi(){long long int m ,n;n = a*c;m = b*d;func(a,b);cout<<" * ";func(c,d);cout<<" = ";func(n,m);cout<<endl;
}
// "/"
void div(){long long int m ,n;n = a*d;m = b*c;func(a,b);cout<<" / ";func(c,d);cout<<" = ";func(n,m);cout<<endl;
}