二进制到十进制转换器与 C

Binary to Decimal Converter with C

我是C语言新手,不太明白为什么这个程序会失败。我觉得这是 isTrue 方法的结果。该方法的目的是确保输入的字符串是一个实际的整数,但它似乎在那里不起作用。我不太确定为什么。由于某种原因,我返回了一些奇怪的值。

/* Program: binToDec.c
   Author: Sayan Chatterjee
   Date created:1/25/17
   Description:
     The goal of the programme is to convert each command-line string
     that represents the binary number into its decimal equivalent 
     using the binary expansion method.
*/

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

/*Methods*/
int strLen(char *str);
int isTrue(char *str);
int signedBinToDec(char *str);

/*Main Method*/
int main(int argc, char **argv)
{
  /*Declaration of Variables*/
  int binNum = 0;
  int decNum = 0;
  int i;

  /*Introduction to the Programme*/
  printf("Welcome to Binary Converter\n");
  printf("Now converting binary numbers\n");
  printf("...\n");

  /*Check to see any parameters*/
  if(argc > 1)
  {
    for(i = 1; i < argc; i++)
    {
      if(isTrue(argv[i] == 1))
      {
        if(strLen(argv[i] <= 8))
        {
          binNum = atoi(argv[i]);
          decNum = signedBinToDec(binNum);
        }
        else
        {
          printf("You did not enter a 8-bit binary\n\a");
          break;
        }
        break;
      }
      else
      {
        printf("You did not enter a proper binary number\n\a");
        break;
      }
    } 

    /*Printing of the Result*/
    printf("Conversion as follows: \n");
    printf("%d\n", decNum);

  }
  else
  {
    printf("You did not enter any parameters. \a\n");
  }
}

int strLen(char *str)
{
  int len = 0;
  while(str[len] != '[=10=]')
  {
    len++;
  }
  return len;
}

int isTrue(char *str)
{
  int index = 0;
  if(str >= '0' && str <= '9')
  {
    return 1;
  }
  else
  {
    return 0;
  }
}


int signedBinToDec(char *str)
{
  int i;
  int len = strLen(str);
  int powOf2 = 1;
  int sum = 0;

  for(i = len-1; i >= 0; i--)
  {
    if(i == 0)
    {
      powOf2 = powOf2 * -1;
    }
    sum = (str[i]*powOf2) + sum;
    powOf2 = powOf2 * 2;
  }
  return sum;
}

if 语句

  if( isTrue(argv[i] == 1) )

大错特错。不好是因为两种情况

  • argv[i] == 1是指针与int的比较,是非法的。这会导致 违反约束 。根据 C11,章节 §6.5.9,等式运算符

    One of the following shall hold:

    — both operands have arithmetic type;

    — both operands are pointers to qualified or unqualified versions of compatible types;

    — one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or

    — one operand is a pointer and the other is a null pointer constant.

  • 比较的结果,同样是一个 int 值,被用作函数参数,而函数应该接受一个 char *intchar * 是不兼容的类型。

看来,你是想写

  if ( isTrue(argv[i]) == 1 )

因为您需要比较 isTrue 调用的 return 值。

strLen(argv[i] <= 8) 和其他人也是如此。


也就是说,还有其他问题。

  • isTrue() 仅检查索引 0 中的值,对于传递的参数,您需要某种循环来检查整个 string.

  • 已经有像isDigit()这样的知名库函数,它的工作非常好,尝试利用它们。