【发布时间】:2020-12-11 12:43:12
【问题描述】:
我是 C 编程新手,不确定我的程序有什么问题。我正在编写一个程序,它将整数作为输入并以二进制形式返回。
输入 43 将输出 101011,但输出为 1。
请指教。
#include <stdio.h>
#include <string.h>
void printBinaryForm( int X )
//Purpose: Print parameter X in binary form
//Output: Binary representation of X directly printed
//Assumption: X is non-negative (i.e. >= 0)
{
//[TODO] CHANGE this to your solution.
int input = X;
char output[] = "";
char binary1 = '1';
char binary2 = '0';
while(input != 0){
if(input%2 != 0){
input = input - 1;
strncat(output, &binary1, 1);
}
else{
input /= 2;
strncat(output, &binary2, 1);
}
}
printf("%s",output);
}
int main(void)
{
int X;
printf("Enter X: ");
scanf("%d",&X);
//print X in binary form
printBinaryForm( X );
return 0;
}
【问题讨论】:
-
最明显的问题是
output是一个单个字符的数组,也就是空字节。这意味着您没有空间在其中存储其他任何东西。strncat调用写入超出数组末尾,导致未定义的行为。 -
打开编译器警告!
-
strncat需要一个字符串,而不是一个字符。
标签: c binary converters