4

我试图通过这个程序将十进制转换为二进制,但输出总是缺少最后一位。

例如,我将为quotient输入“123” ,结果将是“111101”而不是“1111011”。我测试的每个输入都会发生这种情况。每个数字都在正确的位置,除了最后一个,它丢失了。

任何帮助,将不胜感激。

#include <stdio.h>
int main ()
{
    int quotient = 123;
    int i = 0;
    int d1 = quotient % 2;
    quotient = quotient / 2;
    int c = 0;
    int a = 0;
    int number[32] = {};

    while (quotient != 0)
    {
        i = i+1;
        d1 = quotient % 2;
        quotient = quotient / 2;
        c++;
        number[c]=d1;
    }

    for(a = 0; a < c; a = a + 1 )
    {
        printf("%d", number[c-a]);
    }
    return 0;
}
4

2 回答 2

3

问题是你在while循环之前划分了一次:

int d1 = quotient % 2;
quotient = quotient / 2;

将其替换为:

int d1 = 0;

事情应该会更好。

于 2018-09-06T06:59:53.347 回答
1

您的代码中存在以下问题

  1. 应该在while循环中处理。

    int d1 = quotient % 2; quotient = quotient / 2;

  2. c在放入数组之前递增。

  3. 你的 printf 错误 printf("%d", number[c-a]);应该是 printf("%d", number[c-a-1]);

你的完整代码

#include <stdio.h>

int main (){
  int quotient = 15;
  int i = 0;
  int d1;
  //quotient = quotient / 2;
  int c = 0;
  int a = 0;
  int b = 0;
  int number[32] = {};

  while (quotient != 0){
     d1 = quotient % 2;
     quotient = quotient / 2;
     number[c]=d1;
    printf("%d\n", number[c]);
     c++;
  }
  for(a = 0; a < c; a = a + 1 ){
    printf("%d", number[c-a-1]);
  }
  return 0;
}
于 2018-09-06T07:12:13.073 回答