我的数组printf循环最后缺少一个数字

问题描述 投票:4回答:2

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

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

任何帮助,将不胜感激。

#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;
}
c arrays missing-data
2个回答
3
投票

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

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

用以下内容替换:

int d1 = 0;

事情应该更好。


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;
}
© www.soinside.com 2019 - 2024. All rights reserved.