首页 > 学院 > 开发设计 > 正文

1081. Rational Sum (20)

2019-11-08 01:47:03
字体:
来源:转载
供稿:网友

用相减法求最大公约数时要注意开始的时候有个为0的情况

#include<iostream>#include<vector>#include<sstream>#PRagma warning(disable:4996)using namespace std;string chuli(string x, string y){ int a, b, c, d; sscanf(x.c_str(), "%d/%d", &a, &b); sscanf(y.c_str(), "%d/%d", &c,&d); int A = a*d + b*c, B = b*d; a = A > 0 ? A : -A;b = B > 0 ? B : -B; while (a != b) { if (a == 0) { a = b;break; } if (a > b) a = a - b; else b = b - a; } char temp[100]; sprintf(temp,"%d/%d", A / a, B / a); return string(temp);}int main(){ int N; cin >> N; string str; cin >> str; while (--N) { char a[100]; string str1; scanf("%s", a); str1 = a; str = chuli(str, str1); } int a, b; sscanf(str.c_str(), "%d/%d", &a, &b); if (a*b < 0)cout << "-"; a = a > 0 ? a : -a; b = b > 0 ? b:-b; if (a == 0) cout << "0"; if(a/b!=0) cout << a / b; if (a%b != 0) { if (a / b != 0) cout << " "; cout << a%b << "/" << b; } cout << endl;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表