我是一個小菜雞,從來也不放棄努力
阿新 • • 發佈:2018-12-11
Rational Sum (20) 時間限制 1000 ms 記憶體限制 65536 KB 程式碼長度限制 100 KB 判斷程式 Standard (來自 小小) 題目描述 Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum. 輸入描述: Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers "a1/b1 a2/b2 ..." where all the numerators and denominators are in the range of "long int". If there is a negative number, then the sign must appear in front of the numerator. 輸出描述: For each test case, output the sum in the simplest form "integer numerator/denominator" where "integer" is the integer part of the sum, "numerator" < "denominator", and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0. 輸入例子: 5 2/5 4/15 1/30 -2/60 8/3 輸出例子: 3 1/3
#include<cstdio> #include<iostream> using namespace std; int n, a, b,c,d; int gcd(int x, int y) { return y == 0 ? x : gcd(y, x%y); } int lcm(int x, int y) { return x / gcd(x, y)*y; } int main() { cin >> n; scanf("%d/%d", &a, &b); for (int i = 1; i < n; i++) { scanf("%d/%d", &c, &d); int lc = lcm(b, d); a = (lc / b*a + lc / d*c); b = lc; } //cout << a << endl; cout << b << endl; int tt = gcd(a, b);// cout << tt << endl; a /= tt, b /= tt; //格式輸出弄了半天,需要注意。把所以可能的情況都舉個小栗子,然後分類討論 if (a!=0){ if ((a / b) != 0){ if ((a/b) > 0) printf("%d %d/%d\n", a / b, a%b, b); else { if ((a%b)!=0) printf("%d %d/%d\n", a / b,-(a%b) , b); else printf("%d\n", a / b); } } else{ if (a*b > 0){ printf("%d/%d\n", a, b); }else printf("-%d/%d\n", (a<0?-a:a),(b<0?-b:b)); } } else printf("%d\n", a); //cout << (-10 / 3) << endl; cout << (-10 % 3) << endl; system("pause"); return 0; }