我正在编写一个用于在十进制和二进制基数系统之间进行转换的函数,这是我的原始代码:
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/