c语言十进制转二进制浮点,怎样用C语言把二进制浮点数转换成十进制数?

满意答案

00e27ab806e4881f8254fe7ae8741834.png

hs_vblack

推荐于 2016.12.06

00e27ab806e4881f8254fe7ae8741834.png

采纳率:40%    等级:9

已帮助:413人

:-) 终于解决。我写了个程序,只要结果是正确的就行了。

环境: LINUX

编译: gcc -test.c -lm

结果测试:

Please type in a binary number:

101011.01011110011101

The converted decimal number is:

43.368958

#include

#include

int main(void)

{

char binaryNum[100]; /**

* You can not represent a binary number directly in C.

* so i use a character array to store it. See...Anyway

* we just focus on the result, no matter what method

* is considered. :-)

*/

char *p = binaryNum;

double decimalNum = 0;

int n = 0, dotsNum = 0, i = 0, j = 0;

printf("Please type in a binary number:\n");

scanf("%s", &binaryNum);

/**

* CHECK IF THE ENTERED BINARY NUMBER IS LEGAL.

* I USED POINTERS. I TREAT THIS DECIMAL AS TWO

* PARTS: INTEGER & DECIMAL.

*/

for ( ; *p != '\0'; p++, n++) {

if (! (*p == '0' || *p == '1' || *p == '.')) {

printf("bad input!\n");

return 1;

}

if (*p == '.') {

dotsNum++;

if (dotsNum == 1)

i = n;

else {

printf("bad binary number!\n");

return 1;

}

}

}

if (dotsNum)

j = n -1 - i;

else

i = n;

p = binaryNum;

for ( ; i > 0; p++, i--)

if (*p == '1')

decimalNum += pow(2, i -1);

for (p++, i = 1; i <= j; p++, i++)

if (*p == '1')

decimalNum += pow(2, -i);

printf("The converted decimal number is:\n");

printf("%f\n", decimalNum);

return 0;

00分享举报

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值