将 3 位十进制数转换为二进制数 (C)

标签 c binary

我需要使用 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;
}

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

最佳答案

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

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

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

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

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

根据二进制转十进制的规则,应该倒序打印1和0。但是在您的代码中,您更改了顺序。为了解决这个问题,我们可以将结果存储在一个数组中,然后我们可以以倒序打印结果。

这是你修改后的代码,

#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;
}

关于将 3 位十进制数转换为二进制数 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52955008/

相关文章:

c - PlaySound() 与资源文件不工作

iphone - 对创建一个同时具有 iphone 和 iPad 版本的应用程序感到困惑

count - 查找表设置位计数算法的提示

c - C中的面向对象

c - C 语言中的高斯约尔消元法

c# - 动态链接库。如何在 C# 中导入

c - OpenMP-无输出

c - 使用 C 将二进制文件读入结构体,处理 char [8]

c# - LINQ to Entities - 更新二进制字段

python - 如何解码 REG_BINARY 值 HKLM\Software\Microsoft\Ole\DefaultLaunchPermission 以查看哪些用户拥有权限?