【问题标题】:how to fix this code (conversion binary to decimal with char in c)?如何修复此代码(在 c 中使用 char 将二进制转换为十进制)?
【发布时间】:2019-07-09 19:48:35
【问题描述】:

为什么这段代码不起作用? (我想将数字从二进制转换为十进制) 指针有问题?或乘法(char*int)

char cara[100];
char *t=cara;
int i=0;
int sum=0;
int j=0;
int m;

printf("entrer a binary number\n");
scanf("%s",&cara);
while(*t!="\0")
{
    j++;
    m=j-1;
}


for(i=0;i<j;i++)
{
    cara[i]=cara[i]*pow(2,m);
    m--;
}
int k;
for(k=0;k<j;k++)
{
    sum=sum+cara[i];
}
printf("%d",sum);
}

【问题讨论】:

  • while(*t!="\0") 你的编译器说了什么?
  • 编译器什么也没说
  • OT:使用pow 确实没有必要。
  • @mohamedbenhaddou 然后重新编译并启用所有警告。
  • cara[i]=cara[i]*pow(2,m); 错误

标签: c binary


【解决方案1】:

第一个错误在这里:

while(*t!="\0")

您必须对字符使用单引号 - 例如while(*t!='\0')。为了更简单,你可以写while(*t)

除了这个问题,还注意到你从不更新t。您需要在循环中添加++t;

第二个错误在这里:

cara[i]=cara[i]*pow(2,m);

字符'0''1' 确实具有整数值0 和1,因此计算错误。字符'0' 的整数值为48,字符'1' 的整数值为49(参见https://da.wikipedia.org/wiki/ASCII),因此结果将完全错误。

要使计算更正确,您需要:

cara[i] = (cara[i] - '0') * pow(2,m);

但是,将这些中间结果保存回char一个坏主意char 不能保存大于 127 的值(如果 char 是无符号的,则为 255),因此您很快就会出现整数溢出。

一般来说,不需要保存这些中间结果,也不需要pow,因为您可以简单地将每个二进制数字乘以 2。

试试这样:

#include <stdio.h>

int main(void) {
    char *bin_str = "11001";
    unsigned result = 0;
    while (*bin_str)
    {
        result *= 2;
        result += *bin_str == '1' ? 1 : 0;
        ++bin_str;
    }
    printf("%d\n", result);
    return 0;
}

【讨论】:

  • 非常感谢您的帮助和解释。
  • 这是新代码:#include #include #include int main() { char cara[100];字符 *t=cara;诠释我=0;整数总和=0;诠释 j = 0;诠释米; printf("输入一个二进制数\n"); scanf("%s",&cara);而(*t) { ++t; j++; m=j-1; } for(i=0;i
猜你喜欢
  • 2012-02-24
  • 1970-01-01
  • 2017-02-04
  • 2019-09-19
  • 1970-01-01
  • 2021-12-22
  • 2012-12-26
  • 1970-01-01
相关资源
最近更新 更多