Convert Decimal number into Fraction

Posted by alankrita on Stack Overflow See other posts from Stack Overflow or by alankrita
Published on 2012-11-13T16:18:26Z Indexed on 2012/11/13 17:01 UTC
Read the original article Hit count: 179

Filed under:
|

I am trying to convert decimal number into its fraction. Decimal numbers will be having a maximum 4 digits after the decimal place. example:- 12.34 = 1234/100 12.3456 = 123456/10000

my code :-

#include <stdio.h>
int main(void) {
  double a=12.34;
  int c=10000;
  double b=(a-floor(a))*c;
  int d=(int)floor(a)*c+(int)b; 
  while(1) {
     if(d%10==0) {
    d=d/10;
    c=c/10;
 }
 else break;
  }
  printf("%d/%d",d,c);
 return 0;
}

but I am not getting correct output, Decimal numbers will be of double precision only.Please guide me what I should do.

© Stack Overflow or respective owner

Related posts about c

    Related posts about math