我写了一个十进制到二进制转换器,我遇到了一些麻烦 . 它适用于所有小数<16的数字,但对于任何需要二进制长度大于4的数字,它似乎变得混乱,我不知道为什么 .
在运行代码时,无论输入如何,字符串二进制文件的长度始终为3,尽管我声明char数组二进制文件具有大小计数,这正确地显示了表示十进制数所需的二进制数的长度
我必须忽略一些非常基本的东西,但对于我的生活,我看不出它是什么 . 任何帮助,将不胜感激
edit
我认为它必须与使用变量声明char数组的大小有关,我应该使用malloc / calloc吗?
char binary [count]; int length = strlen(二进制); 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;
}
1 回答
binary
这里已经分配但没有初始化为任何东西 . 它可以包含任何东西 - 那么你期望它的长度是多少?