c++ - 十进制转二进制

标签 c++ while-loop evaluation conditional-statements boolean-expression

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

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)

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

最佳答案

当你说 while (number) 时,number,它是一个 int,被转换为类型 bool。如果为零,则变为 false,如果为非零,则变为 true

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

关于c++ - 十进制转二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769376/

相关文章:

c++ - 我可以通过网络同步/备份 RocksDB 吗?

c++ - 使用 Windows API 操作 RS 端口

c++ - 在 Lua 中创建回调函数

bash - bash 中嵌套循环的奇怪行为

javascript - 如果第一个条件失败,为什么 javascript 会评估多个 AND 条件

c++ - 如何重新创建树,其中序遍历存储在文件中

java - 当条件设置为 false 时,While 循环执行最后一次

php - 如何使用 while 循环统计并显示 php 的所有信息?

python - 评估集群性能

haskell - Haskell 中的算术表达式求值