当前位置: 代码迷 >> 综合 >> bjfu1011 Convert decimal to fraction
  详细解决方案

bjfu1011 Convert decimal to fraction

热度:15   发布时间:2024-01-13 04:26:37.0

Convert decimal to fraction

时间限制(C/C++):1000MS/3000MS          运行内存限制:65536KByte
总提交:202            测试通过:47

描述

As we all know, every decimal can be converted to a fractional number.
So you please write a program to do this, not only ordinary decimal, but also circulating decimal, and remember that the result must be fraction in lowest term.

输入

The input consists of multiple test cases.
Each test case consists a Pure decimal (decimal without integer part), and the cyclic part should be enclosed buy brackets.And the length of each data would be less than 15 characters.

输出

For each test case, print each fraction in lowest term in a line.

样例输入

0.25
0.(5)
0.32(692307)

样例输出

1/4
5/9
17/52

题目来源

ben


题意:小数变分数,括号内的无限循环。
AC代码:
#include<iostream>  
#include<math.h>  
#include<string>  
using namespace std;  
void gcd(__int64 m,__int64 n){  __int64 a=m,b=n,c;  while(b!=0){  c=b;          b=a%b;          a=c;      } if(m==0){ printf("0\n"); return; }  if(a!=0)  printf("%I64d/%I64d\n",m/a,n/a);  return;      
}  
__int64 powhaha(__int64 l){ __int64 ans=1,a=10; while(l>0){ if(l%2==1) ans*=a; l/=2; a*=a; } return ans; } 
int main(){  __int64 d,num,wei,len,i,g;  string s; while(cin>>s){  num=wei=0; d=g=0;  len=s.length(); for(i=2;i<len;i++)  if(s[i]=='('){ g++; break; } if(g==0){         for(i=2;i<len;i++)  num=num*10+s[i]-48;  wei=powhaha(len-2); gcd(num,wei);          }  else if(s[2]=='('){        for(i=3;i<len-1;i++)  num=num*10+s[i]-48;  wei=powhaha(len-4)-1;  gcd(num,wei);          }  else{  for(i=2;i<len;i++){  if(s[i]!='('){  wei=wei*10+s[i]-48;                      d=d*10+9;                  }  else break;  }  for(i=2;i<len;i++){  if(s[i]==')')  break;  if(s[i]!='(')  num=num*10+s[i]-48;  else continue;  }  num=num-wei;  wei=powhaha(len-4)-1;  wei=wei-d;  gcd(num,wei);         }      }  return 0;  
} 

  相关解决方案