1

我正在编写一个用于在十进制和二进制基数系统之间进行转换的函数,这是我的原始代码:

void binary(int number)
{
    vector<int> binary;

    while (number == true)
    {
        binary.insert(binary.begin(), (number % 2) ? 1 : 0);
        number /= 2;
    }

    for (int access = 0; access < binary.size(); access++)
        cout << binary[access];
}

但是在我这样做之前它没有用:

while(number)

怎么了

while(number == true)

这两种形式有什么区别?提前致谢。

4

2 回答 2

8

当你说while (number),number这是一个int, 被转换为 type bool。如果它是零,它变成false,如果它是非零,它变成true

当你说while (number == true)时, thetrue被转换为int(成为1),就像你说的一样while (number == 1)

于 2011-04-24T07:57:31.157 回答
0

这是我的代码....

    #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<unistd.h>
#include<assert.h>
#include<stdbool.h>
#define max 10000
#define RLC(num,pos) ((num << pos)|(num >> (32 - pos)))
#define RRC(num,pos) ((num >> pos)|(num << (32 - pos)))

void tobinstr(int value, int bitsCount, char* output)
{
    int i;
    output[bitsCount] = '\0';
    for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
      {
             output[i] = (value & 1) + '0';
      }
}


  int main()
   {
    char s[50];
    tobinstr(65536,32, s);
    printf("%s\n", s);
    return 0;
   }
于 2012-02-03T09:49:01.420 回答