分数求和

总时间限制: 
1000ms
内存限制: 
65536kB
描述

输入n个分数并对他们求和,并用最简形式表示。所谓最简形式是指:分子分母的最大公约数为1;若最终结果的分母为1,则直接用整数表示。

如:5/6、10/3均是最简形式,而3/6需要化简为1/2, 3/1需要化简为3。

分子和分母均不为0,也不为负数。

输入
第一行是一个整数n,表示分数个数,1 <= n <= 10;
接下来n行,每行一个分数,用"p/q"的形式表示,不含空格,p,q均不超过10。
输出
输出只有一行,即最终结果的最简形式。若为分数,用"p/q"的形式表示。
样例输入
2
1/2
1/3
样例输出
5/6

  • 题解:
  • 我先把第一个分数作为初值,然后不断和下一个分数先通分,后相加。
    例如1/2和1/3先通分为3/6和2/6,然后分子相加得5/6。

  • 最后再约分,方法是分子分母同时除以gcd(分子,分母)

  • 代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<stack>
#include<queue>
#define MAXA 10000
typedef long long LL;
using namespace std;
int n,son,mother,s,m;
char ch;
int gcd(int a,int b) {
	if(b == 0)
	   return a;
	return gcd(b,a%b);
}
int main() {
	scanf("%d",&n);
	scanf("%d %c %d",&son,&ch,&mother);
	s = son;m = mother;
	for(int i=1;i<=n-1;i++) {
		scanf("%d %c %d",&son,&ch,&mother);
		int temp_m = m,temp_mother = mother;
		m *= temp_mother; s *= temp_mother;
		mother *= temp_m; son *= temp_m;
		s += son;
	}
	if(gcd(s,m) == 1) {
		if(m != 1) {
			printf("%d/%d",s,m);
		    return 0;
		}
		else {
			printf("%d",s);
			return 0;
		}
	}
	else {
		int simplify = gcd(s,m);
		s /= simplify;
		m /= simplify;
		if(m == 1) {
			printf("%d",s);
			return 0;
		}
		printf("%d/%d",s,m);
		return 0;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值