c语言输入参数是一个正整数,输出该整数所对应的二进制数对应的字符串。
时间: 2023-06-10 19:03:30 浏览: 110
C语言字符串的输入和输出
好的,您可以使用以下的 C 语言代码实现该功能:
```c
#include <stdio.h>
#include <stdlib.h>
char *int_to_binary_string(unsigned int num) {
char *bin_str = malloc(33 * sizeof(char)); // Allocating memory for the binary string
if (bin_str == NULL) {
fprintf(stderr, "Failed to allocate memory!\n");
exit(1);
}
bin_str[32] = '\0'; // Setting NULL terminator
// Calculating binary string
for (int i = 31; i >= 0; i--) {
bin_str[i] = (num & 1) ? '1' : '0'; // Extracting bit and converting to character
num >>= 1; // Shifting number to right by one bit
}
return bin_str;
}
int main() {
unsigned int num;
printf("Enter a positive integer: ");
scanf("%u", &num);
char *bin_str = int_to_binary_string(num);
printf("Binary representation: %s\n", bin_str);
free(bin_str); // Freeing memory allocated for binary string
return 0;
}
```
此代码会提示输入一个正整数,然后输出它的二进制表示。
阅读全文