Q:将输入的二进制转换为十进制表达。
#include"stdio.h" #include"math.h" int biTode(int n,int *sum,int *m) { char c; scanf("%c",&c); if(c!='#') { *m=*m+1; biTode(n+1,&(*sum),&(*m)); } if(c=='1') *sum=*sum+pow(2,(*m)-n-1); } int main() { int sum=0,m=0; printf("input a binary number ending for '#' "); biTode(0,&sum,&m); printf("the decimal digit is "); printf("%d ",sum); return 0; }
分析:算法中参数sum用来记录累加和。参数m随着递归的深入不断加1,并且递归结束m的值也不会发生变化。因为参数sum和m都要在递归中保持值得不变,因此采用指针传递方式。参数n的值随着递归的深入不断加1,但是每一层的递归n的取值都不同。在将二进制转换为十进制时,2的指数应为(*m)-n-1.输入的二进制数以字符形式存储,当输入字符#时,表示二进制字符串输入结束。在调用该算法时,参数的初值都为0。