【发布时间】:2013-09-21 23:00:57
【问题描述】:
我用 C 语言编写了一个程序,将浮点数 represented in binary (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;
}
【问题讨论】:
-
这个问题并不真正适合 Stackoverflow 格式。它基本上是“我的代码中有一个错误,你能找到它吗?”而不是“这件事没有按预期工作”。尝试减少问题的特殊性并创建最小的测试用例。如果您可以稍微改一下,这里有一个非常有效的问题。
-
您的问题是 1101.11 不能表示为
double。你得到(除非你有不常见的doubles)1101.109999999999899955582804977893829345703125。这会破坏你的算法。 -
I have gone through the code many time- 查看它,还是使用调试器进行调试?看看scanf()读入bin的实际 值是多少。我敢打赌,这不是完全 1101.11 -
@BiswajitPaul 也编辑了一点,希望这会更清楚:)
-
printf("%f", ...)的默认精度为 6 位小数。如果在小数点后 6 位以下存在不精确(提示:有),您将不会看到这样的结果。扫描后立即尝试printf("%.24f\n", bin)'。
标签: c floating-point floating-point-conversion