-2

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

#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

4

3 回答 3

2

您的代码有几个问题:

  • 您只需要一个,而不是两个循环
  • 您正在使用代表数字的字符,即'0'or '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
}

这是关于 ideone 的演示

于 2013-03-28T00:38:00.147 回答
1
p = 1; sum = 0;
for(n=strlen(s)-1;n>=0;n--)
{
    sum += (s[n] - '0') * p;
    p = p << 1;
}

我推荐上面的代码,而不是你的双倍循环。

于 2013-03-28T00:34:34.637 回答
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; 
}
于 2013-03-28T01:17:06.300 回答