繁体   English   中英

十进制到二进制转换器无法正常工作

[英]Decimal to binary converter not working correctly

我已经写了一个十进制到二进制转换器,并且遇到了一些麻烦。 对于所有小于16的十进制数字,它都可以正常工作,但是对于任何需要大于4的二进制长度的数字,它似乎很麻烦,我不确定为什么。

在运行代码时,无论输入如何,字符串二进制的长度始终为3,尽管我声明了char数组二进制的大小为count ,这正确显示了表示十进制数所需的二进制数的长度

我必须忽略一些真正基本的东西,但是对于我的一生,我看不到它是什么。 任何帮助,将不胜感激

编辑

我认为这一定与使用变量声明char数组的大小有关,我应该使用malloc / calloc吗?

char binary [count];

int length = strlen(binary);

printf(“字符串长度为%d \\ n”,长度);

#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已分配但未初始化为任何东西。 它可能包含任何内容-那么您期望长度是多少?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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