PAT L1-009. N个数求和(辗转相除法,浮点和输出注意)
2016-12-07 09:57
459 查看
题目地址
https://www.patest.cn/contests/gplt/L1-009ac代码
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <string> #include <vector> #include <queue> #include <algorithm> #include <sstream> #include <stack> #include <map> #include <set> #include <unordered_map> using namespace std; const int INF = 0x7fffffff; const int MIN_INF = - INF -1; typedef long long int LL; // 最大公约数 LL gcs(LL n , LL m) { if(n < m) { LL tmp = n; n = m; m = tmp; } // n >= m LL r = n % m; while(r != 0) { n = m; m = r; r = n % m; } return m; } int n; int main() { //freopen("in.txt","r",stdin); while(scanf("%d", &n) != EOF) { LL a1 = 0, b1 = 1; LL a2, b2; for(int i=0;i<n;i++) { scanf("%lld/%lld",&a2,&b2); if(a2 == 0) { continue; } LL yue = gcs(b1,b2); LL gong = b1 * b2 / yue; LL tmp1 = a1 * gong / b1; LL tmp2 = a2 * gong / b2; LL tmp = tmp1 + tmp2 ; if(tmp == 0) { a1 = 0; b1 = 1; continue; } LL flag = 1; if(tmp < 0){ flag = -1; tmp = -tmp; } LL yue2 = gcs(tmp, gong); a1 = flag * tmp / yue2; b1 = gong / yue2; } if(a1 == 0){ printf("0\n"); }else{ if(a1 < 0) { printf("-"); a1 = -a1; } if(b1 == 1) { printf("%lld\n",a1); }else{ if(a1 % b1 == 0) { printf("%lld\n", a1 / b1); }else{ LL t = a1 / b1; LL t2 = a1 % b1; if(t != 0) { printf("%lld ",t); printf("%lld/%lld\n", a1 - t * b1, b1); }else{ printf("%lld/%lld\n", a1 - t * b1, b1); } } } } }// end while //printf("\n"); return 0; }
相关文章推荐
- PAT-L1-009. N个数求和(辗转相除法应用)
- PAT-L1-009 N个数求和
- L1-009. N个数求和-PAT团体程序设计天梯赛
- PAT 天梯赛 L1-009 N个数求和
- PAT L1-009. N个数求和
- PAT L1-009. N个数求和 模拟
- PAT-团体程序设计天梯赛-练习集-L1-009. N个数求和
- PAT练习集之20分题-L1-009. N个数求和
- PAT L1-009. N个数求和 分数求和 struct重载
- PAT-L1-009. N个数求和
- PAT-L1-009. N个数求和
- PAT L1-009. N个数求和
- PAT - 天梯赛 L1-009 N个数求和
- 【题解搬运】PAT_L1-009 N个数求和
- PAT 天梯赛 L1-009 N个数求和
- Java - PAT - L1-009. N个数求和
- L1-009. N个数求和 - PAT
- L1-009. N个数求和-PAT团体程序设计天梯赛GPLT
- PAT L1 009 N个数求和
- L1-009. N个数求和