码迷,mamicode.com
首页 > 其他好文 > 详细

小数化为最简分式 (hdu 1717)

时间:2015-08-19 23:46:08      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

hdu 1717 小数化分数

分析:

无限小数可按照小数部分是否循环分成两类:无限循环小数和无限不循环小数。
无限不循环小数不能化分数;

考虑:无限循环小数又是如何化分数的呢?
例如:0.325656……×100=32.5656……①
0.325656……×10000=3256.56……②
用②-①即得:
0.325656……×9900=3256.5656……-32.5656……
0.325656……×9900=3256-32
所以, 0.325656……=3224/9900

代码:


 #include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
#include<algorithm>
using namespace std;
#define LL long long
#define clr(a,b) memset(a,b,sizeof a)

char str[12];

LL  Gcd(LL a, LL b)
{
    return b==0 ? a : Gcd(b, a%b);
}
int main()
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    #endif // ONLINE_JUDGE
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",str);
        int len=strlen(str);
        LL tot,num;
        tot=0;
        num=1;
        LL xx,yy;
        xx=0;
        yy=1;
        bool flag=0;
        for(int i=1; i<len; i++){
            if(str[i]>=‘0‘&&str[i]<=‘9‘){
                tot=tot*10+(str[i]-‘0‘);
                num*=10;
            }
            if(str[i]==‘(‘)   flag=1;
            if(!flag&&str[i]>=‘0‘&&str[i]<=‘9‘){
                 xx=xx*10+(str[i]-‘0‘);
                 yy*=10;
            }
        }

        if(num!=yy)  num-=yy;
        if(tot!=xx)  tot-=xx;
        //cout<<tot<<" "<<num<<" "<<xx<<" "<<yy<<endl;
        LL  kk=Gcd(tot,num);
        //cout<<kk<<endl;
        cout<<tot/kk<<"/"<<num/kk<<endl;
        //printf("%d/%d\n",tot/kk,num/kk);

    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

小数化为最简分式 (hdu 1717)

标签:

原文地址:http://blog.csdn.net/u013514722/article/details/47790423

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!