#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;
}
当然这题也可以直接用等比数列算