函数原型如下:
double binTodec(char *str);
其中str为接收的二进制数,函数的返回值为对应的十进制数。
如输入:
1010
则输出为:
10.000000
又如输入:
100.11
则输出为:
4.75
#include "stdio.h"
double binTodec(char *str){
int i,f;
double x,t;
for(t=1.0,x=f=i=0;str[i];i++){
if(str[i]=='.')
f=1;
else if(f==0)
(x*=2)+=str[i]-'0';
else
x+=(str[i]-'0')*(t/=2);
}
return x;
}
int main(int argc,char *argv[]){
char a[20];
printf("Please enter a binary number...\n");
scanf("%[0-9.]",a);
printf("%s --> %f\n",a,binTodec(a));
return 0;
}
double binTodec(char *str){
int i,f;
double x,t;
for(t=1.0,x=f=i=0;str[i];i++){
if(str[i]=='.')
f=1;
else if(f==0)
(x*=2)+=str[i]-'0';
else
x+=(str[i]-'0')*(t/=2);
}
return x;
}
int main(int argc,char *argv[]){
char a[20];
printf("Please enter a binary number...\n");
scanf("%[0-9.]",a);
printf("%s --> %f\n",a,binTodec(a));
return 0;
}
运行样例:
温馨提示:答案为网友推荐,仅供参考