【发布时间】:2014-04-25 05:38:20
【问题描述】:
在这里我从我的代码中添加函数,用于从给定的二进制数生成浮点数。
代码:
double binary_float(double f) /* Function to convert binary to float.*/
{
long integral = 0, floatInt = 0, i = 1, temp1 = 0, k = 1;
double floatFract = 0, fractional = 0, floatTotal = 0;
//Separating the integral value from the floating point variable
integral = (long)f;
//Separating the fractional value from the variable
fractional = f - (long)f;
//Converting binary to decimal
floatInt = binary_decimal(integral);
//Loop for converting binary to Fractional value
while( k < 10000000 && fractional != (double)0 )
{
k = k * 10;
i = i * 2;
temp1 = (long)(fractional * k);
printf("temp: %ld, r: %lf\n", temp1, (fractional * k));
floatFract = floatFract + (double)temp1/(double)i;
printf("fact: %lf, r: %lf\n", floatFract, ((double)temp1/(double)i));
fractional = fractional - (double)temp1/(double)k;
printf("frac: %lf, r: %lf\n", fractional, ((double)temp1/(double)k));
}
//Combining both the integral and fractional binary value.
floatTotal = floatInt + floatFract;
return floatTotal;
}
long binary_decimal(long n)
{
long decimal=0, i=0, rem;
while (n!=0)
{
rem = n%10;
n/=10;
decimal += rem*pow(2,i);
++i;
}
return decimal;
}
输出:
Enter a binary number: 1010.001100
temp: 0, r: 0.011000
fact: 0.000000, r: 0.000000
frac: 0.001100, r: 0.000000
temp: 0, r: 0.110000
fact: 0.000000, r: 0.000000
frac: 0.001100, r: 0.000000
temp: 1, r: 1.100000
fact: 0.125000, r: 0.125000
frac: 0.000100, r: 0.001000
temp: 0, r: 1.000000
fact: 0.125000, r: 0.000000
frac: 0.000100, r: 0.000000
temp: 9, r: 10.000000
fact: 0.406250, r: 0.281250
frac: 0.000010, r: 0.000090
temp: 9, r: 10.000000
fact: 0.546875, r: 0.140625
frac: 0.000001, r: 0.000009
temp: 9, r: 10.000000
fact: 0.617188, r: 0.070312
frac: 0.000000, r: 0.000001
1010.001100 in binary = 10.617188 in float
在输出中您可以看到 temp: 0, r: 1.000000 表示 temp1 = 0 是 1.000000 的 long 类型转换。
谁能解释一下为什么这种类型转换不起作用?
【问题讨论】:
标签: c type-conversion