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

#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 == 0 ? a : gcd(b, a % b);
}
int main()
{
    char a[200];
    while(~scanf("%s",a))
    {
        int len = strlen(a);
        int pos1 = -1,pos2 = -1;
        for(int i = 0; i < len; i++)
        {
            if(a[i] == '(')
            {
                pos1 = i;
            }
            if(a[i] == ')')
            {
                pos2 = i;
            }
        }
        if(pos1 == pos2)
        {
            int sum = 0,num,tot = 0;
            for(int i = len-1;a[i] != '.';i--)
            {
                num = a[i] - '0';
                sum += powl(10,len-1-i) * num;
                tot++;
            }
            tot = powl(10,tot);
           // cout<<"sum = "<<sum<<endl;
           // cout<<"tot = "<<tot<<endl;
            int gc1 = gcd(tot,sum);
            cout<<sum/gc1<<"/"<<tot/gc1<<endl;
        }
        else
        {
            int sum1 = 0,tot1 = 0;
            for(int i = 2;a[i] != '(';i++)
            {
                sum1 *= jw;
                sum1 += a[i] - '0';
                tot1++;
            }
            int sum2 = 0,tot2 = 0;
            for(int i = pos1+1;i < pos2;i++)
            {
                sum2 *= jw;
                sum2 += a[i] - '0';
                tot2++;
            }
            tot1 = powl(10,tot1);
            tot2 = powl(10,tot2) - 1;
            int num1 = sum1 * tot2 + sum2;
            int num2 = tot1 * tot2;
            int gc2 = gcd(num1,num2);
            cout<<num1/gc2<<"/"<<num2/gc2<<endl;
        }
    }
}
原文地址:https://www.cnblogs.com/jifahu/p/5449026.html