从二进制转换为十进制

时间:2013-03-28 00:27:55

标签: c

代码应该将二进制数转换为十进制数,但事实并非如此。任何人都可以检查我可能出错的地方。

#include <stdio.h>
#include <math.h>
#include <string.h>

int main()
{

    char s[40];
    int base;
    int index,n,p,sum=0;     /* n is the number of digits in the converted value */

    printf("enter the number and base: ");
    scanf("%s %d",s,&base);

    for(n=strlen(s)-1;n>=0;n--)
    {
        p=strlen(s);
        for(index=strlen(s)-(p-1); index<=p; index++)
        {
        sum += s[index] * pow(base,n);
        }
    }
    printf("decimal no. is %d",sum);
    printf("\n");

}

输出:

enter the number and base:1011
2

十进制没有。是1487

3 个答案:

答案 0 :(得分:2)

您的代码存在一些问题:

  • 您只需要一个而不是两个循环
  • 您使用的是代表数字的字符,即'0''1',而不是数字的值
  • 你的数学有点偏差:在pow(base,n)中,n应该替换为从后面开始的数字位置。

以下是修改代码的方法:

// Power starts at the length-1
p=strlen(s)-1;
for(index=0; index < strlen(s); index++, p-- /* <<< Power counts down */)
{
    sum += (s[index]-'0') * pow(base,p);
    //               ^^^-- Note the minus '0' above:
    //                     That's what gives you a digit's value
}

这是demo on ideone

答案 1 :(得分:1)

p = 1; sum = 0;
for(n=strlen(s)-1;n>=0;n--)
{
    sum += (s[n] - '0') * p;
    p = p << 1;
}

我推荐上面的代码,而不是你的双周期。

答案 2 :(得分:0)

我的回答是:

#include <stdio.h>
#include <math.h>
#include <string.h> 
int main(int argc, char *argv[]){
    char s[40];
    int base;
    int index,n,p,sum=0;/*n is the number of digits in the converted value */
    printf("enter the number and base: ");
    scanf("%s %d",s,&base);

    p = strlen(s);
    index = 0;
    for(n = 40 - p - 1; n >= 0; n--)
        sum += (s[n] - '0') * pow(base, index++);
    printf("decimal no. is %d",sum);
    printf("\n");
    return 0; 
}
相关问题