简体   繁体   English

程序打印全1?

[英]Program printing all 1's?

I want to have a number filled with 1's and 0's and convert it to boolean. 我想用1和0填充数字并将其转换为布尔值。 However, when I run my code, it print's out all 1's. 但是,当我运行代码时,它打印出的全为1。 My code 我的密码

I have almost all of the code finished, i know i'm just missing a piece possibly. 我几乎完成了所有代码,我知道我可能会丢失一部分。

unsigned int booltoint(char number[], int length)
{
  int i;
  bool check;
  for(i = 0; i < length; i++)
{
    if(number[i] == 0)
    {
      check = false;
      printf("%d\n", check);
    }
    else
    {
      check = true;
      printf("%d\n", check);
    }
   }
  return check;
}


int main()
{
  int length;
  char number[] = "11001100";


  length = strlen(number);
  booltoint(number, length);

}

The issue is that you're comparing a char type with an int type. 问题是您正在比较char类型和int类型。

While a char is technically an int, it's based in ASCII values . 从技术上讲,char是一个int,但它基于ASCII值 This means that, when you get the char at index i of char array number, you're returning the printable version of that char. 这意味着,当您在char数组编号的索引i处获得char时,您将返回该char的可打印版本。

For example: 例如:
char '0' = int 48 char'0'=整数48
char '1' = int 49 char'1'=整数49
(You can see these values in the linked chart.) (您可以在链接的图表中看到这些值。)

Your check will always return false because no ASCII value is 0 (expect NULL, but that's another story). 您的检查将始终返回false,因为没有ASCII值是0(期望为NULL,但这是另一回事)。

The easiest (and most readable/maintable) way to correct the equality check is like this: 纠正相等性检查的最简单(也是最易读/可维护)的方法是这样的:

if (number[i] == '0')

or 要么

if (number[i] == '1')

To see the ASCII representation of different numbers, you could run something like this: 要查看不同数字的ASCII表示形式,可以运行以下命令:

int  i;

for (i=32; i<127; i++) {
    printf("%d: '%c'\n", i, i);
}

This is also a good time to learn about bit values as they relate to ASCII and control characters. 这也是学习与ASCII和控制字符相关的位值的好时机。

If you want to compact your code so it's easier to see what's really happening, look into the ternary operator. 如果要压缩代码,以便更轻松地了解实际情况,请查看三元运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM