简体   繁体   中英

Decimal to binary converter not working correctly

I have written a decimal to binary converter and am having some trouble with it. It works fine for all decimal numbers < 16, but for any numbers that require a binary length larger than 4 it seems to go haywire and I'm not sure why.

When running the code, no matter the input, the length of the string binary is always 3, despite me declaring the char array binary to be of size count , which is correctly displaying the length of the binary number needed to represent the decimal number

I must be overlooking something really basic, but for the life of me I can't see what it is. Any help would be appreciated

edit

I presume it must be something to do with declaring the size of the char array with the use of a variable, should I instead be using malloc/calloc?

char binary[count];

int length = strlen(binary);

printf("Length of string is %d \\n", length);

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

int main()
{
    int input;
    int decimal;
    int count;

    printf("Please enter a number \n");
    scanf("%d", &input);

    decimal = input;
    count = floor(log(decimal)/ log(2)) +1;

    printf("Length of binary needed %d \n", count);
    char binary[count];
    int length = strlen(binary);
    printf("Length of string is %d \n", length);
    for(count; count >= 0; count--)
    {
        if(pow(2, count) <= decimal)
        {
            decimal -= pow(2, count);
            binary[length - count] = '1';
        }
        else
            binary[length - count] = '0';

    }
    printf("%d is represented by %s in binary \n", input, binary);
    return 0;
}
char binary[count];
int length = strlen(binary);

binary here has been allocated but not initialised to anything. It could contain anything - so what do you expect the length to be?

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