简体   繁体   English

将十进制数转换为对应的二进制数@Love babbar

[英]Convert a decimal number to its corresponding binary @Love babbar

Can anyone tell me why is this code not giving proper answer for odd numbers but it is giving right answers for even numnbers.谁能告诉我为什么这段代码没有给出奇数的正确答案,但它给出了偶数的正确答案。

 **int main(){
  int n;
  cin>> n;

  int ans = 0;
  int i = 0;
  while(n != 0){
    int bit = n & 1;
    ans = (bit * pow(10, i)) + ans;
    n = n >> 1;
    i++;
  }
  cout<<ans;
}**

Change pow(10, i) to pow(2, i) , since binary works in powers of 2, not powers of 10. Also (side note), you can change the while loop to a for loop concerning incrementing i :pow(10, i)更改为pow(2, i) ,因为二进制以 2 的幂而不是 10 的幂工作。另外(旁注),您可以将while循环更改为关于递增ifor循环:

for (int i = 0; n != 0; i++)
{
    //convert n to binary
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM