L1-009 N个数求和

在这里插入图片描述
在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
struct Fraction//分数结构体 
{
	int fenZi;//分子 
	int fenMu;//分母 
	Fraction(int fenZi0,int fenMu0):fenZi(fenZi0),fenMu(fenMu0){}
	Fraction(){}
	Fraction operator + (Fraction& f)//重载加法运算 
	{
		int factor=gcd(fenMu,f.fenMu);
		int newFenMu=fenMu/factor*f.fenMu;
		int newFenZi=fenZi*newFenMu/fenMu+f.fenZi*newFenMu/f.fenMu;
		Fraction newf=Fraction(newFenZi,newFenMu);
		newf.reduction();
		return newf;
	}
	
	void reduction()//约分 
	{
		int factor=gcd(abs(fenZi),abs(fenMu));
		fenZi/=factor;
		fenMu/=factor;
	}	
	
	int gcd(int x,int y)//求最大公约数 
	{
		if(x==0||y==0)
			return 1;
		int r;
		r=x%y;	
		while(r!=0)
		{
			x=y;
			y=r;
			r=x%r;
		}
		return y;
	} 
	
	void disp()//带分数形式输出 
	{
		int zhengShu=fenZi/fenMu;
		if(zhengShu!=0)
		{
			cout<<zhengShu;
			int t1,t2;
			t1=abs(fenZi)%fenMu;
			t2=fenMu;
			if(t1!=0)
			{
				cout<<" "<<t1<<"/"<<t2;
			}
		}
		else
		{
			if(fenZi!=0)
			{
				cout<<fenZi<<"/"<<fenMu;
			}
			else
			{
				cout<<0;
			}
		}
	}
};

int main(void)
{
	int n;
	cin>>n;
	Fraction sum=Fraction(0,1);
	while(n--)
	{
		Fraction f;
		scanf("%d/%d",&(f.fenZi),&(f.fenMu));
		f.reduction();
		sum=sum+f;
	}
	sum.disp();
	cout<<endl;
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值