Segmentation failure (recorded core image) decimal to binary conversion

Asked

Viewed 69 times

0

#include <stdio.h>
int main() {

int d;
int bits = 8;
int vetor[bits];
int a = bits - 1;
int b = a;

    scanf("%d", &d);

    if(d >= 2) {
    while(d/2 > 0){
        vetor[a] = b % 2;
        b /= 2;
        a--;
        b--;
        }

    for(a=0; a<b; a++)
        vetor[a] = 0;
    vetor[b] = 1;
    for(a=0; a<bits; b++)
    printf("%d", vetor[a]);
    }

        else if(d >= 1) {
                for(a=0; a<b; a++)
    printf("%d", vetor[a] = 0);
    printf("%d", vetor[a] = 1);
    }

    else if(d >= 0) {
                for(a=0; a<bits; a++)
    printf("%d", vetor[b] = 0);

    }
    else printf("\n Numero invalido!");

    printf("\n");


return 0;
}
  • You noticed that in the print loop you are assigning the value 0 to vetor[b]? And therefore not printing the value of vetor[b]?

  • I don’t know what I could do to correct the error, even changing the value of the same error.

1 answer

0


In while(d/2 > 0){ vetor[a] = b % 2; b /= 2; a--; b--; }

vector change[a] = b % 2; per vector[a] = d % 2 and change b /= 2; for d /=2;

In for(a=0; a<bits; b++) printf("%d", vetor[a]); trade b++ for a++

  • worked out very obg

Browser other questions tagged

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