分数的表示

#include <iostream>
#include <cmath>
using namespace std;
int g(int a, int b){//求最大公约数 
	int t;
	if(a < b){
		t = b;
		b = a;
		a = t;
	}
	return !b ? a : g(b, a%b);//如果 b == 0返回a,否则返回g(b, a%b); 
}
struct Fraction{//定义分数的结构体 
	int up, down;
};
Fraction reduction(Fraction result){//约分函数 
	if(result.down < 0){
		result.down = -result.down;
		result.up = -result.up;
	}
	if(result.up == 0){
		result.down = 1;
	}else{
		int d = g(abs(result.up), abs(result.down));
		result.up /= d;
		result.down /= d;
	}
	return result; 
}
int Showresult(Fraction r){
	r = reduction(r);
	if (r.down == 1) cout << r.up;
	else cout << r.up << "/" << r.down;
}
int main()
{
	Fraction r;
	cin >> r.up >> r.down;
	reduction(r);
	Showresult(r);
	return 0;
} 

在这里插入图片描述

#include <iostream>
using namespace std;
typedef long long ll;
int gcd(ll a, ll b){
  ll t;
  if(a < b){
    t = b;
    b = a; 
    a = t;
  }
  return !b ? a : gcd(b , a % b);
}
struct Fraction{
    long long up, down;
};
Fraction reduction(Fraction r){
  int d = gcd(r.up, r.down);
  r.up /= d;
  r.down /= d;
  return r;
}
void show(Fraction r){
  cout << r.up << "/" << r.down <<endl;;
}
Fraction Plus(Fraction f1, Fraction f2){
  Fraction m;
  m.up = f1.up * f2.down + f2.up * f1.down;
  m.down = f1.down * f2.down;
  return reduction(m);
}
int main()
{
  // 请在此输入您的代码
  Fraction c, p, s;
  p.up = 1;
  p.down = 1;
  c.up = 0;
  c.down = 1;
  for (int i = 0; i < 20; i++){
    s = Plus(c, p);
    c = s;
    p.down = 2 * p.down;
  }
  show(s);
  return 0;
}

当然这题也可以直接用等比数列算

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值