简体   繁体   中英

My array printf loop is missing one digit at the end

I'm trying to convert decimal to binary via this program, but the output is always missing the last digit.

For example, I'll input "123" for quotient , and the result will be "111101" instead of "1111011". This happens for every input I test. Every digit is in the right place, except for the last one, which is missing.

Any help would be appreciated.

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

The problem is that you're dividing once before the while loop :

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

Replace that with just :

int d1 = 0;

and things should work better.

You have the following problems in your code

  1. should be handled in while loop.

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

  2. You are incrementing the c before putting into the array.

  3. Your printf is wrong printf("%d", number[ca]); should be printf("%d", number[ca-1]);

Your full code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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