View Code of Problem 3494

#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;

int fun(int m, int n) {//求最大公约数
	m = abs(m);        //带绝对值防止分母出现负数
	n = abs(n);
	if (m == n) return m;
	if (m < n) {
		int t;
		t = m; m = n; n = t;
	}
	int temp;
	while (m % n != 0) {
		temp = m;
		m = n;
		n = temp % n;
	}
	return n;
}
int main() {
	int a, b, c, d;
	char o,e='/';
	while (cin >>a>> e >> b >> o >> c >> e >> d) {
		int fenmu=0, fenzi=0;
		fenmu = b * d / fun(b, d);
		if (o == '+') {
			fenzi = a * fenmu / b + c * fenmu / d;
		}
		if(o=='-') {
			fenzi = a * fenmu / b - c * fenmu / d;
		}
		if (fenzi == 0) cout << 0 << endl;
		else if (fenzi == fenmu) cout << 1 << endl;
		else {
			if (fenzi % fenmu == 0) cout << fenzi/fenmu<<endl;
			else cout << fenzi / fun(fenzi, fenmu) << e << fenmu / fun(fenzi, fenmu) << endl;
		}

	}
	return 0;
}

Double click to view unformatted code.


Back to problem 3494