十进制到二进制转换

1 c++ evaluation boolean-expression while-loop conditional-statements

我正在为Decimal和Binary基数系统之间的转换编写一个函数,这是我的原始代码:

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];
}
Run Code Online (Sandbox Code Playgroud)

然而,在我这样做之前它没有用:

while(number)
Run Code Online (Sandbox Code Playgroud)

怎么了?

while(number == true)
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*lis 8

当你说while (number),numberint,是,转换为类型bool.如果它为零则变为false,如果它为非零则变为true.

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