Decimal to torque converter in C

Asked

Viewed 19,547 times

5

I’m doing a code in C for a college job in order to convert a decimal number to binary. But when the program runs, it always prints out 00000000, no matter what number I put in. Would anyone know what the mistake is? Follows the code:

#include <stdio.h>
#include <stdlib.h>

int main() {

    int num;
    int bin[7];
    int aux;

    printf("Digite o número (base decimal) para ser convertido: ");
    scanf("%d", &num);

    for (aux = 7; aux >= 0; aux--) {
        if (num % 2 == 0) {
            bin[aux] = 0;
            num = num / 2;
        }
        else {
            bin[aux] = 1;
            num = num / 2;
        }
    }

    for (aux = 0; aux <= 7; aux++) {
        printf("%d", bin[aux]);
    }

    return 0;
}
  • 2

    What would be the logic you used in the line num = (num / 2) - 0.5;? This subtraction of 0.5 does not make much sense (remembering that the variable is of the type int, so when an odd value is divided by two, the result is rounded down; for example, 5/2 = 2).

  • It needs to work for negative numbers?

  • True, I fixed that part, but the problem remains. No need for negative numbers

  • https://repl.it/HUEA/0 here worked perfectly. How you are testing?

  • I did it in Dev-C++... it’s probably a compiler problem so

  • Related: https://answall.com/q/286742/64969

  • 1

    @Jeffersonquesado is not duplicated because of the recursion. The case here is more close as a problem that cannot be reproduced. I tested the code here and it worked. Woss over a year ago also tested and it also worked.

  • @Jeffersonquesado It’s closer to the question you related in April this year.

Show 4 more comments

1 answer

1

I could not reproduce the reported error, but there is an error in the "bin" array declaration, which by its logic needs to have 8 elements. Other than that, nothing seems to be wrong.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int num;
   int bin[8]; // <---------------
   int aux;

   printf("Digite o número (base decimal) para ser convertido: ");
   scanf("%d", &num);

   for (aux = 7; aux >= 0; aux--)
   {
      if (num % 2 == 0)
         bin[aux] = 0;
      else
         bin[aux] = 1;
      num = num / 2;
   }

   for (aux = 0; aux < 8; aux++)
       printf("%d", bin[aux]);

   printf("\n");

   return 0;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.