代码如下:
#include <stdio.h>
#include <stdlib.h>
int *dec2bin(int N, int *n);
int *dec2bin(int N, int *n) {
int l = 0;
do {
if (N % 2 == 0) {
n[l] = 0;
l++;
} else {
n[l] = 1;
l++;
}
N = N / 2;
} while (N != 0);
return n;
}
int main() {
int N = 0;
int *n = NULL;
n = malloc(sizeof(int));
do {
printf("type an integer\n");
scanf("%d", &N);
} while (N <= 0 || N > 65535);
n = dec2bin(N, n);
int l = n[0];
printf("the binary equivalent of %d is: ", N);
n = realloc(n, (l + 1) * sizeof(int));
for (int i = l; i >= 1; i--) {
printf("%d", n[i]);
}
return 0;
}
程序应该吐出一个整数的二进制数:
我的问题是程序编译但
printf
函数中的main
我认为不起作用或者是dec2bin
有问题但我认为它更多地与printf
有关。
我试了很多。问了一个小时的聊天 gpt,也尝试了几个小时自己可能出错的地方,但我就是找不到错误。这就是我发布这个问题的原因
您应该使用
main
中定义的具有自动存储(本地数组)的数组,而不是分配长度为 1 条目的数组,其长度足以满足 int
中的最大位数。
建议使用
unsigned int
类型以避免对负值产生意外结果。
dec2bin
应该返回数组中设置的位数。
这里是修改版:
#include <limits.h>
#include <stdio.h>
int dec2bin(unsigned int N, int *n) {
int i = 0;
do {
n[i++] = N % 2;
N = N / 2;
} while (N != 0);
return i;
}
int main(void) {
unsigned int N;
int bits[sizeof(N) * CHAR_BIT]; // 32 on most current platforms
int n;
int c;
printf("type an integer\n");
while (scanf("%u", &N) != 1 || N > 65535) {
/* read and discard the remaining characters on the input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF) {
printf("invalid input. Premature end of file\n");
return 1;
}
printf("invalid input. Enter a number between 0 and 65535\n");
}
n = dec2bin(N, bits);
printf("the binary equivalent of %u is: ", N);
for (int i = n; i-- > 0;) {
printf("%d", bits[i]);
}
printf("\n");
return 0;
}
如果你不能改变
int *dec2bin(unsigned int N, int *n)
函数的原型dec2bin
,这个函数必须计算固定数量的比特,否则调用者将无法知道已经计算了多少比特。鉴于对 N
的值的约束,dec2bin
应该传递一个 16
整数数组并计算精确的 16 位值。这些位的生成顺序是规范问题。
这里是修改版:
#include <stdio.h>
int *dec2bin(unsigned int N, int *n) {
for (int i = 0; i < 16; i++) {
n[i] = N % 2;
N = N / 2;
}
return n;
}
int main(void) {
unsigned int N;
int bits[16];
int c;
printf("type an integer\n");
while (scanf("%u", &N) != 1 || N > 65535) {
/* read and discard the remaining characters on the input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF) {
printf("invalid input. Premature end of file\n");
return 1;
}
printf("invalid input. Enter a number between 0 and 65535\n");
}
dec2bin(N, bits);
printf("the binary equivalent of %u is: ", N);
for (int i = 16; i-- > 0;) {
printf("%d", bits[i]);
}
printf("\n");
return 0;
}
使用您的代码,稍作调整。
我相信这个解决方案与使用 n 数组保存存储位长度的原始问题一致。
#include <stdio.h>
#include <stdlib.h>
int *dec2bin(int N, int *n) {
int l = 1;
do {
n = realloc(n, (l + 1) * sizeof(int)); // expand n array
if (N % 2 == 0) {
n[l] = 0;
l++;
} else {
n[l] = 1;
l++;
}
N = N / 2;
} while (N != 0);
n[0]=l-1; // #bits stored here
return n;
}
int main() {
int N = 0;
int *n = NULL;
n = malloc(sizeof(int));
do {
printf("type an integer\n");
scanf("%d", &N);
} while (N <= 0 || N > 65535);
n = dec2bin(N, n);
for (int i = n[0] ; i > 0; i--) {
printf("%d", n[i]);
}
return 0;
}
祝你好运