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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值