满意答案
hs_vblack
推荐于 2016.12.06
采纳率: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分享举报