十进制到二进制转换
我正在编写一个用于十进制和二进制基数系统之间转换的函数,这是我的原始代码:
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)
以及有什么区别? 提前致谢。
I was writing a function for conversion between Decimal and Binary base number systems and here's my original code:
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];
}
It didn't work however until I did this:
while(number)
what's wrong with
while(number == true)
and what's the difference between the two forms?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您说
while (number)
时,number
(int
)将转换为类型bool
。如果它为零,则变为false
,如果它非零,则变为true
。当您说
while (number == true)
时,true
会转换为int
(变为1
) 与您所说的while (number == 1)
是一样的。When you say
while (number)
,number
, which is anint
, is converted to typebool
. If it is zero it becomesfalse
and if it is nonzero it becomestrue
.When you say
while (number == true)
, thetrue
is converted to anint
(to become1
) and it is the same as if you had saidwhile (number == 1)
.这是我的代码......
Here is my code....