L1-009 N个数求和(入门20分 含易错点)

L1-009 N个数求和

本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数分子/分母的形式给出的,你输出的和也必须是有理数的形式。

易错点

  1. 浮点错误:除数或者取余为0
  2. 运行超时:求最小公倍数用递归会超时
#include
using namespace std;
long int ele1 = 0, dom1 = 0;
//进行约分
void yuefen(long int& a, long int& b) {
	long int max = a > b ? a : b;
	long int min = a > b ? b : a;
	long int c = 1;
	//当分子为0时候
	if (min == 0)
		a = 0;
	else {
		c = max % min;
		while (c != 0) {
			max = min;
			min = c;
			c = max % min;
		}// min
		a = a / min;
		b = b / min;
	}
}
//jieguo 
void jieguo(long int a, long int b) {
	if (a == 0)
		cout << 0;
	else if (a / b == 0 )
		cout << a << "/" << b << endl;
	else if (a % b == 0)
		cout << a / b << endl;
	else
		cout << a / b << " " << a % b << "/" << b << endl;
} 
void add(long int ele, long int dom, int i, int num) {
	//long int ele1 = 0, dom1 = 0;
	if (i == 0) 
		ele1 = ele, dom1 = dom;
	else {
		long int mutiple = dom1* dom;//最小公倍数用递归会超时
		long int mutiple_ele = (mutiple / dom1) * ele1 + (mutiple / dom) * ele;
		yuefen(mutiple_ele, mutiple);//yuefen finished
		ele1 = mutiple_ele; dom1 = mutiple;
        if (i == num - 1)
		    jieguo(ele1, dom1);
	}
}
int main() {
	int num; cin >> num;
	char c; 
	long int ele; 
	long int dom;
	for (int i = 0; i < num; i++) {
		cin >> ele >> c >> dom;
		add(ele, dom, i, num);
	}
	return 0;
}

你可能感兴趣的:(团体程序设计天梯赛)