本文主要是介绍1081. Rational Sum 解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
分数的求和,还是规成求最大公因数的问题。
注意讨论各种情况,整数,真分数,假分数。
#include <iostream>using namespace std;int n;long long gcd(long long a, long long b) {if (b == 0) return a;else return gcd(b, a%b);
}int main() {cin >> n;long long fra1, num1,fra2,num2;cin >> fra1;cin.get();cin >> num1;for (int i = 1; i < n; i++) {cin >> fra2;cin.get();cin >> num2;fra1 = fra1 * num2 + fra2 * num1;num1 = num1*num2;}if (fra1 == 0) {cout << 0 << endl;return 0;}long long factor = gcd(fra1, num1);fra1 /= factor;num1 /= factor;if (fra1 % num1 == 0) { //整数cout << fra1 / num1 << endl;}else if (fra1 < num1) { //真分数cout << fra1 << "/" << num1 << endl;}else {long long dec = fra1 / num1;fra1 %= num1;cout << dec << " " << fra1 << "/" << num1 << endl;}return 0;
}
这篇关于1081. Rational Sum 解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!