PAT乙级1034
Posted wx630c98f24f6b8
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT乙级1034相关的知识,希望对你有一定的参考价值。
1034. 有理数四则运算(20)
时间限制
200 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue
本题要求编写程序,计算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>
#include<algorithm>
using namespace std;
struct fraction
long long a, b;
long long k;
fraction():k(0)
;
int gcd(long long a, long long b)
return !b ? a : gcd(b, a%b);
fraction reduction(fraction f)
fraction ft;
if (f.b < 0)
ft.a = -f.a;
ft.b = -f.b;
f.a = -f.a;
f.b = -f.b;
if (f.a == 0)
ft.a = 0;
ft.b = 1;
f.a = 0;
f.b = 1;
ft.a= f.a/gcd(abs(f.a), f.b);
ft.b= f.b/gcd(abs(f.a), f.b);
if (abs(ft.a) >= ft.b)
if (f.a < 0)
ft.k = -abs(ft.a) / ft.b;
ft.a = abs(ft.a) % ft.b;
else
ft.k = abs(ft.a) / ft.b;
ft.a = abs(ft.a) % ft.b;
return ft;
fraction add(fraction f1, fraction f2)
fraction f;
f.a = f1.a*f2.b + f2.a*f1.b;
f.b = f1.b*f2.b;
return reduction(f);
fraction substract(fraction f1, fraction f2)
fraction f;
f.a = f1.a*f2.b - f2.a*f1.b;
f.b = f1.b*f2.b;
return reduction(f);
fraction multiply(fraction f1, fraction f2)
fraction f;
f.a = f1.a*f2.a;
f.b = f1.b*f2.b;
return reduction(f);
fraction divide(fraction f1, fraction f2)
fraction f;
f.a = f1.a*f2.b;
f.b = f1.b*f2.a;
return reduction(f);
void printFraction(fraction f)
if (f.k > 0)
if (f.a != 0)
cout << f.k << " " << f.a << "/" << f.b;
else
cout << f.k;
else if (f.k == 0)
if (f.a > 0)
cout << f.a << "/" << f.b;
else if (f.a == 0)
cout << 0;
else
cout << "(" << f.a << "/" << f.b << ")";
else
if (f.a != 0)
cout << "(" << f.k << " " << f.a << "/" << f.b<<")";
else
cout << "(" << f.k << ")";
int main()
fraction f1, f2;
scanf("%lld/%lld %lld/%lld", &f1.a, &f1.b, &f2.a, &f2.b);
printFraction(reduction(f1));
cout << " + ";
printFraction(reduction(f2));
cout << " = ";
printFraction(add(f1, f2));
cout << endl;
printFraction(reduction(f1));
cout << " - ";
printFraction(reduction(f2));
cout << " = ";
printFraction(substract(f1, f2));
cout << endl;
printFraction(reduction(f1));
cout << " * ";
printFraction(reduction(f2));
cout << " = ";
printFraction(multiply(f1, f2));
cout << endl;
printFraction(reduction(f1));
cout << " / ";
printFraction(reduction(f2));
cout << " = ";
if (f2.a != 0)
printFraction(divide(f1, f2));
else
cout << "Inf";
cout << endl;
return 0;
以上是关于PAT乙级1034的主要内容,如果未能解决你的问题,请参考以下文章