简体   繁体   English

十进制转二进制错误

[英]decimal to binary conversion error

I am trying to create a program that converts decimal to binary and prints 0b before the binary.我正在尝试创建一个将十进制转换为二进制并在二进制之前打印 0b 的程序。

I need the program to print 0b0 if 0 is the input, and 0b11101 when input is 29. I can seem to do one, but not the other, and when I fix that bug, the other stops working如果输入为 0,我需要程序打印 0b0,当输入为 29 时打印 0b11101。我似乎可以做一个,但不能做另一个,当我修复那个错误时,另一个停止工作

Where am I going wrong ?我哪里错了?

#include <stdio.h>
int main()
{

int n,i = 0,j=0,k;

scanf("%d",&n);
int bin[100];

    k=n;

    //printf("n is %d \n",n);
    while(n!=0)
    {
        //printf("n is %d :\n",n);
     bin[i]= n%2;
        //printf ("n/2 is  %d\n",n%2);
     n=(n-n%2)/2;
     i++;
        //printf("i is %d\n",i);
    }
printf("0b");
    //if (n='0')
    //{
    //  printf("0");
    //}


    //else
    //{
        for (j=i;j>0;j--)
        {
            //printf("\n j is,%d and there ,is %d\n",j,bin[(j-1)]);
            printf("%d",bin[(j-1)]);

        }
    //}

}

0 does not need to be treated as a special case. 0 不需要被视为特殊情况。 Simply fix: use a do loop rather than while () .只需修复:使用do循环而不是while ()

#include <stdio.h>
int main() {
  int n,i = 0,j=0,k;
  scanf("%d",&n);
  int bin[100];
  // k=n;  // not needed

  // while(n!=0) {
  do {
    bin[i]= n%2;

    // Another simplification
    // n=(n-n%2)/2;
    n /= 2;

    i++;
  } while (n);
  printf("0b");
  for (j=i;j>0;j--) {
    printf("%d",bin[(j-1)]);
  }
}

Other coding needed to handle n<0 .处理n<0所需的其他编码。

#include <stdio.h>
int main()
{
int n,i = 0,j=0,k;
scanf("%d",&n);
int bin[100]; 
k=n;
    while(n!=0)
    {
     bin[i]= n%2;
     n=(n-n%2)/2;
     i++;
    }
printf("0b");
    if (k==0)
    {
      printf("0");
    }
    else
    {
        for (j=i-1;j>=0;j--)
        {
            printf("%d",bin[(j-1)]);
        }
    }
}

A naive and more portable implementation of a decimal to binary conversion function ...十进制到二进制转换函数的一种天真且更便携的实现......

#include <limits.h>

void print_binary(unsigned x){
    unsigned n=UINT_MAX;

    n = ~(n >> 1);

    while (n){ 
        if (n & x)
            putchar('1');
        else
            putchar('0');
        n = n >> 1;
    }
    putchar('\n');
}

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

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