1. 程式人生 > >PAT B1034 有理數四則運算 (20 分)

PAT B1034 有理數四則運算 (20 分)

lean tdi 括號 sys string const ace 輸出 遍歷

本題要求編寫程序,計算 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
作者: CHEN, Yue 單位: 浙江大學 時間限制: 200 ms 內存限制: 64 MB 代碼長度限制: 16 KB

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
const int maxn = 100010
; struct num{ long long k = 0; long long up; long long down; }; int gcd(long long a, long long b){ return b == 0 ? a : gcd(b, a % b); } num add(num n1, num n2){ num res; res.down = n1.down*n2.down; res.up = n1.down*n2.up + n1.up*n2.down; return res; } num sub(num n1, num n2){ num res; res.down
= n1.down*n2.down; res.up = n2.down*n1.up - n2.up*n1.down; return res; } num mul(num n1, num n2){ num res; res.down = n1.down*n2.down; res.up = n1.up*n2.up; return res; } num dive(num n1, num n2){ num res; res.down = n1.down*n2.up; res.up = n1.up*n2.down; if (res.down < 0){ res.down = -1 * res.down; res.up = -1 * res.up; } return res; } void clean(num n){ int flag = 0; n.k = n.up / n.down; if (n.up < 0){ n.up = -n.up; flag = 1; } n.up = n.up%n.down; int g = abs(gcd(n.up, n.down)); n.up /= g; n.down /= g; if (flag == 1){ printf("("); } if (n.k != 0){ printf("%lld", n.k); if (n.up != 0){ printf(" %lld/%lld", n.up, n.down); } } else{ if (n.up != 0){ if (flag == 1)printf("-"); printf("%lld/%lld", n.up, n.down); } else{ printf("0"); } } if (flag == 1){ printf(")"); } } int main(){ num n1, n2; scanf("%lld/%lld %lld/%lld", &n1.up, &n1.down, &n2.up, &n2.down); /*int g = abs(gcd(n1.up, n1.down)); n1.up /= g; n1.down /= g; g = abs(gcd(n2.up, n2.down)); n2.up /= g; n2.down /= g;*/ num q, w, e, r; q = add(n1, n2); clean(n1); printf(" + "); clean(n2); printf(" = "); clean(q); printf("\n"); w = sub(n1, n2); clean(n1); printf(" - "); clean(n2); printf(" = "); clean(w); printf("\n"); r = mul(n1, n2); clean(n1); printf(" * "); clean(n2); printf(" = "); clean(r); printf("\n"); if (n2.up != 0){ e = dive(n1, n2); clean(n1); printf(" / "); clean(n2); printf(" = "); clean(e); printf("\n"); } else{ clean(n1); printf(" / "); clean(n2); printf(" = Inf\n"); } system("pause"); }

註意點:這道題的坑有兩個,一個是int不夠大,兩個大int乘起來就爆了,要用long long,long long 的輸入輸出要用lld。第二個是約分,求最大公約數,遍歷就超時了,要用輾轉相除法,一定要記住!!!

PAT B1034 有理數四則運算 (20 分)