Problem Links:
poj3979,
Problem:
分数加减法
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5903 | Accepted: 1884 |
Description
编写一个C程序,实现两个分数的加减法
Input
输入包含多行数据
每行数据是一个字符串,格式是"a/boc/d"。
其中a, b, c, d是一个0-9的整数。o是运算符"+"或者"-"。
数据以EOF结束
输入数据保证合法
每行数据是一个字符串,格式是"a/boc/d"。
其中a, b, c, d是一个0-9的整数。o是运算符"+"或者"-"。
数据以EOF结束
输入数据保证合法
Output
对于输入数据的每一行输出两个分数的运算结果。
注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数
注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数
Sample Input
1/8+3/8 1/4-1/2 1/3-1/3
Sample Output
1/2 -1/4 0
Source
Solution:
PS: Take care of each situation that could happen.
1st, if the numerator is 0;
2nd, if they have gcd greater than 1 after the operation.
Source Code:
//Mon Nov 22 23:32:14 CST 2010#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int main(int argc, const char* argv[])
{
// freopen("input.in", "r", stdin);
// freopen("output.out", "w", stdout);
int a, b, c, d;
char ch1, ch2;
while (cin >> a >> ch1 >> b >> ch2 >> c >> ch1 >> d)
{
//cout << a << b << c << d << endl;
int temp = b / gcd(b, d) * d;
int flag = 1;
switch (ch2)
{
case '+':
a = a * (temp / b) + c * (temp / d);
break;
case '-':
a = a * (temp / b) - c * (temp / d);
flag = a < 0 ? -1 : 1;
a = a < 0 ? -a : a;
}
int temp2 = gcd(a, temp);
//cout << temp2 << endl;
a /= temp2;
temp /= temp2;
if(a == 0) //One WA here w/o considering if a is 0;
{
cout << "0" << endl;
continue;
}
if(temp == 1)
{
cout << a*flag << endl; //One WA here w/o *flag;
continue;
}
cout << a * flag << "/" << temp << endl;
}
// fclose(stdin);
// fclose(stdout);
return 0;
}
No comments :
Post a Comment