不要让昨天 占据你的今天 夏午晴天

夏午晴天

有限小数化为最简分数

/*

请将有限小数化为最简分数。

Input

一个整数n 表示需要转化的小数个数; 接下来n行,每行有一个有限小数。(保证小数位数不超过9位)

Output

输出有n行,每行为小数对应的最简分数

Sample Input

2
0.5
0.4

Sample Output

1/2 2/5

注意精度问题,数据保证不会有类似1.0的小数。

*/

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int Gcd(int a,int b){
    if(a<b){
        int t;
        t = a;
        a = b;
        b = t;
    }
    return b!=0?Gcd(b,a%b):a;
}
char str[50],str2[50];
int main() {
    int t,i,k,count,big,small,mul1,mul2,gcd,sum;
    cin>>t;
    while(t--)
        {
        cin>>str;
        count = 0;
        int len = strlen (str);
        for(i=0; i< len;i++){
            if(str[i]!='.'){
                count++;

            }
            else{
                break;
            }
        }

        mul1 = mul2 = 1;
        sum = big = small = 0;
        for(i=0; i<count; i++){//整数

            big = str[i]-'0'+ big*10;
            mul1 *= 10;
        }
        for(i=count+1; i<strlen(str); i++){ //小数

            small = str[i]-'0'+ small*10;
            mul2 *= 10;
        }

        big*=mul2;
        sum+=(big + small);
        gcd = Gcd(sum,mul2);
        cout<<sum/gcd<<'/'<<mul2/gcd<<endl;

    }
    return 0;
}

posted on 2017-02-21 15:55  夏晴天  阅读(292)  评论(0编辑  收藏  举报

导航

Live2D