将二进制浮点“1101.11”转换为十进制(13.75)的正确算法?

Bis*_*aul 3 c floating-point floating-point-conversion

我用 C 编写了一个程序,将二进制( ) 表示的浮点数转换1101.11为十进制 ( 13.75)。

但是,我似乎无法从算法中获得正确的值。

将二进制浮点数转换为十进制的正确方法是什么?

我正在使用 Dev CPP 编译器(32 位)。该算法定义如下:

void b2d(double p, double q )
{
   double rem, dec=0, main, f, i, t=0;

   /* integer part operation */    
   while ( p >= 1 )
   {
     rem = (int)fmod(p, 10);
     p = (int)(p / 10);
     dec = dec + rem * pow(2, t);
     t++;
   }

   /* fractional part operation */
   t = 1; //assigning '1' to use 't' in new operation
   while( q > 0 )
   {
     main = q * 10;
     q = modf(main, &i); //extration of frational part(q) and integer part(i)
     dec = dec+i*pow(2, -t);
     t++;
   }

   printf("\nthe decimal value=%lf\n",dec); //prints the final output
}

int main()
{
   double bin, a, f;

   printf("Enter binary number to convert:\n");
   scanf("%lf",&bin);

   /* separation of integer part and decimal part */
   a = (int)bin;
   f = bin - a;       
   b2d(a, f); // function calling for conversion

   getch();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Use*_*ess 5

正如您所相信的那样,您并不是将“1101.11”读取为以二进制表示的浮点数。您正在将其读取为转换为 IEEE 双精度浮点值的以 10 为基数的浮点数然后尝试更改基数。

这个中间步骤固有的不精确性是您出现问题的原因。

正如 Vicky 所建议的,更好的方法是:

  1. 将“1101.11”读取为字符串或文本行
  2. 转换整数部分和小数部分(whole=b1101=13numerator=b11=3, denominator=4
  3. 将这些重新组合成whole + numerator/denominator = 13.75