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;
}
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 typeint, so when an odd value is divided by two, the result is rounded down; for example, 5/2 = 2).– Woss
It needs to work for negative numbers?
– Anthony Accioly
True, I fixed that part, but the problem remains. No need for negative numbers
– Silvestre
https://repl.it/HUEA/0 here worked perfectly. How you are testing?
– Woss
I did it in Dev-C++... it’s probably a compiler problem so
– Silvestre
Related: https://answall.com/q/286742/64969
– Jefferson Quesado
Possible duplicate of How to obtain the representation of a positive integer in binary, using recursion?
– Jefferson Quesado
@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.
– Victor Stafusa
@Jeffersonquesado It’s closer to the question you related in April this year.
– Victor Stafusa