日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

PAT B1034 有理数四则运算 (20 分)

發布時間:2025/3/15 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 PAT B1034 有理数四则运算 (20 分) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本題要求編寫程序,計算 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。第二個是約分,求最大公約數,遍歷就超時了,要用輾轉相除法,一定要記住!!!

轉載于:https://www.cnblogs.com/tccbj/p/10363287.html

總結

以上是生活随笔為你收集整理的PAT B1034 有理数四则运算 (20 分)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。