首页 > 解决方案 > 将 3 位十进制数转换为二进制 (C)

问题描述

我需要使用 C 将 3 位十进制数转换为二进制数。

我的代码:

#include <stdio.h> 

#define TWO 2 

int main() {
    int dec_num; // demical number  
    int i = 0; // loop cunter 
    printf("type in 3 digits number to convert to binary\n"); 
    scanf("%d", &dec_num); 

    while (++i <= 12) {
        if (dec_num % TWO != 0) {
            printf("1") ;
        } else if (dec_num % TWO == 0) {
            printf("0"); 
        } else if (dec_num <= 0) {
            break; 
        }
        dec_num / TWO;
    }
    return 0;
}

问题是这个数字在循环结束时没有除以 2我该while如何解决?

标签: cbinary

解决方案


您没有存储dec_num除法后的值。

 dec_num / TWO; //<--------------------

您的 while 循环条件也是错误的。

while(++i <= 12) //<-------------------

您应该执行除法运算,直到数字大于 0

根据二进制转十进制的规则,应该在reverse order. 但是在您的代码中,您更改了顺序。为了解决这个问题,我们可以将结果存储在 an 中array,然后我们可以将结果打印到reverse order.

这是您修改后的代码,

#include <stdio.h> 
#define TWO 2 

int main()
{
  int dec_num; // demical number  
  int i=0; // loop cunter 
  printf("type in 3 digits number to convert to binary\n"); 
  int flag = scanf("%d",&dec_num); //<-----check the user input
  if(flag!=1)
    {
  printf("Input is not recognized as an integer");
  return 0;
    }
  int size=0;  

  int array[120] = {0};  //<-------to store the result

  while(dec_num > 0){   //<------- while the number is greater than 0

      if(dec_num % TWO !=0){
          array[i] = 1;
         }
      else if(dec_num % TWO ==0){
          array[i] = 0;
          }

      size = ++i;  //<------- store the size of result

     dec_num = dec_num / TWO;  //<------- divide and modify the original  number
  }

  for(i=size-1;i>=0;i--)    //<------- print in reverse order
      printf("%d",array[i]);

  return 0;
}

推荐阅读