二进制到十进制...错误的输出

Binary to decimal...wrong output

#include<stdio.h>
#include<string.h>
#include<math.h>
int main()
{          
    char *bin=malloc(sizeof(char)*100);
    int i=0,p=0,dec=0,g;

    printf("\nenter the binary number\n");
    gets(bin);
    i=strlen(bin)-1;
    while(*(bin+p)!=NULL){

        if(*(bin+p)=='1'){
            g=pow(2,(i-p));
            dec=dec+g;
        }
        p++;
    }
    printf("\n%d",dec);

return 0;
}

以上程序应将任何位二进制数转换为十进制数。

示例输入:

10011

预期输出:

19

实际输出:

1

除了已经指出的 gets 问题之外,您的代码中还有一些 } 不匹配。但是逻辑缺少 i 的值。在您的代码中,您从始终为 0 的 i 中减去 p。尝试在循环之前设置 i 的值,就像这样 -
i = strlen(bin) - 1;

此外,还要在您的代码中添加一些错误检查。

大家已经指出了各种问题。除此之外,您可能希望按如下方式更改您的程序。还要记住,为了演示,我在程序中设置了 bin 的值。您仍想获取 bin.

的用户输入
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
int main()
{

char *bin=(char *)malloc(sizeof(char)*100);
int i=0,p=0,dec=0,g;

printf("\nenter the binary number\n");
//gets(bin);
bin = "1011";
int len = strlen(bin);
i = len;

while(i > 0)
{
    if(*(bin+p)=='1')
    {
        g=pow(2,(len-p-1));
        dec=dec+g;
    }
    p++;
    i--;
}
printf("\n%d",dec);

return 0;
}

第一:打开编译器警告。编译你的代码时我收到了几个警告和一个编译器错误。

也就是说,pow函数的使用有误。您可以通过将 i 设置为适当的值来修复它:

gets(bin);
i = strlen(bin) - 1;

如果输入正确(只有 1 和 0,不超过 int 中的位数),这将使代码工作。

您还应该将 gets 替换为 fgets:

fgets(bin, 100, stdin);

请注意,如果字符串适合,fgets 也会将换行符放入字符串中,因此您需要将其删除。

修复了我在使用 gcc -Wall 编译时收到的警告后,代码如下所示(我没有费心将 gets 更改为 fgets):

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

int main()
{
  char *bin=malloc(sizeof(char)*100);
  int i=0,p=0,dec=0,g;

  printf("\nenter the binary number\n");
  gets(bin);
  i = strlen(bin) - 1;

  while(*(bin+p)!='[=12=]'){
    if(*(bin+p)=='1'){
      g=pow(2,(i-p));
      dec=dec+g;
    }
    p++;
  }
  printf("\n%d",dec);

  return 0;
}

希望这能解决您的问题。

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

int main()
{          
char *bin = (char *) malloc(sizeof(char)*100);
int i=0, p =0,dec=0,g;

printf("\nenter the binary number\n");
gets(bin);
i = strlen(bin);
i = i - 1;
while(*(bin+p)!='[=10=]'){

    if((*(bin+p))=='1'){
        g=pow(2,(i-p));
        dec=dec+g;
    }
    p++;
}
printf("\n%d",dec);
return 0;
}