转换十进制数为分数 [英] Convert Decimal number into Fraction

查看:163
本文介绍了转换十进制数为分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想十进制数转换成它的一部分。十进制数将具有小数点后最多4位数。
例如: - 12.34 =100分之1234
12.3456 =一万分之十二万三千四百五十六

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

我的code: -

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;
}

但我没有得到正确的输出,十进制数将是双precision的only.Please指导我我应该做的。

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

推荐答案

如果您的浮点数是 X ,那么分数超过10000的分子将是不可或缺的的一部分(X + 0.00005)* 10000 。是否要减少分数简单的术语(即由分子和分母的最大公约数划分出),这取决于你。

If your floating point number is x, then the numerator of the fraction over 10000 will be the integral part of (x + 0.00005) * 10000. It's up to you whether you want to reduce the fraction to simplest terms (i.e. divide out by the gcd of the numerator and denominator).

这篇关于转换十进制数为分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆