【问题标题】:C Program for converting binary number to decimal isn't working用于将二进制数转换为十进制的 C 程序不起作用
【发布时间】:2020-12-30 18:21:15
【问题描述】:

以下是我编写的用于将二进制数转换为十进制的 C 程序,但它总是给出输出“0”。有人能指出错误吗?

#include<stdio.h>
main()
{
int a=1/2,p=0,rem,n;
printf("Enter a binary number:");
scanf("%d",&n);
while(n!=0)
{
    a=a*2;
    rem=n%10;
    p=p+rem*a;
    n=n/10;
}
printf("Its decimal equivalent is %d",p);
}

【问题讨论】:

  • int a=1/2 等价于int a = 0
  • 是的,你说得对。所以我做了修改并声明'a'为float a=1/2;而且还是不行
  • 初始化a = 1并将a=a*2;移动到循环的最后一行。因为a 是 2 的幂,所以二进制数字乘以它应该是1, 2, 4, 8, etc。旁注:使用描述性变量名称(power_of_2 而不是 a 等)和空格(a = a * 2; 不是 a=a*2;)更容易阅读您的代码。有些人可能会争论最后一点。
  • 谢谢。这解决了我的问题。另外,我会在编码时记住这一点

标签: c windows binary type-conversion decimal


【解决方案1】:

当您在 c 中除整数时,它会围绕解决方案。 所以如果你想将 a/b 计算为浮点数,你需要像这样a/(float)b

【讨论】:

    猜你喜欢
    • 2020-09-02
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2022-01-01
    • 2016-01-17
    相关资源
    最近更新 更多