hrbustoj 1125 循环小数 II(小数变分数+极限思想)

时间:2021-03-23 06:52:49
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<map>
#include<iostream>
using namespace std;
#define jw 10
///小小的总结了一下
///没有循环的方式略,当有循环的时候,就要用到0.999999... = 1的知识了
///0.99999.. = (9/10)+(9/100)+(9/1000)+(9/10000)+....+(9/10^n)
/// = (1/10 + 1/100 + 1/1000 ...)*9 左边由等比数列求和公式得到1/9 * (1 - 1/10^n);
/// n->+oo,左式为1/9,证明成立,代码中第二种方式原理与其一致
int gcd(int a,int b)
{
return b == ? a : gcd(b, a % b);
}
int main()
{
char a[];
while(~scanf("%s",a))
{
int len = strlen(a);
int pos1 = -,pos2 = -;
for(int i = ; i < len; i++)
{
if(a[i] == '(')
{
pos1 = i;
}
if(a[i] == ')')
{
pos2 = i;
}
}
if(pos1 == pos2)
{
int sum = ,num,tot = ;
for(int i = len-;a[i] != '.';i--)
{
num = a[i] - '';
sum += powl(,len--i) * num;
tot++;
}
tot = powl(,tot);
// cout<<"sum = "<<sum<<endl;
// cout<<"tot = "<<tot<<endl;
int gc1 = gcd(tot,sum);
cout<<sum/gc1<<"/"<<tot/gc1<<endl;
}
else
{
int sum1 = ,tot1 = ;
for(int i = ;a[i] != '(';i++)
{
sum1 *= jw;
sum1 += a[i] - '';
tot1++;
}
int sum2 = ,tot2 = ;
for(int i = pos1+;i < pos2;i++)
{
sum2 *= jw;
sum2 += a[i] - '';
tot2++;
}
tot1 = powl(,tot1);
tot2 = powl(,tot2) - ;
int num1 = sum1 * tot2 + sum2;
int num2 = tot1 * tot2;
int gc2 = gcd(num1,num2);
cout<<num1/gc2<<"/"<<num2/gc2<<endl;
}
}
}