【发布时间】:2022-10-05 14:01:24
【问题描述】:
所以我正在解决一个问题,要求我将用户输入字符串更改为 ASCII,然后以递归方式二进制。我设法为单个字符执行此操作,但是当我尝试使用 for 循环时,它会给我带来一个奇怪的结果。谁能帮我解决这个问题?
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
int main()
{
char toBS;
printf(\"Enter the string you want to convert: \\n\");
scanf(\"%c\", &toBS);
int i;
for (i = 0; i<toBS+1; i++){
print(toBS);
}
printf(\"\\n\");
return;
}
void print(char c)
{
int n = CHAR_BIT;
binaryPrinter((unsigned char)c, &n);
putchar(\'\\n\');
}
void binaryPrinter(int value, int *numberOfOnes)
{
if((*numberOfOnes)--){
binaryPrinter(value >> 1, numberOfOnes);
printf(\"%d\", value & 1);
}
}
这是我的结果:
输入:a
输出:
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
01100001
-
为什么这个函数是递归的?为什么不使用
sizeof(unsigned char)*8而不是CHAR_BIT?为什么numberOfOnes是指针?我的问题多于答案。 -
提示:这将是完全琐碎的与一个简单的
for循环有关。 -
要么你的缩进被破坏了,要么你的编码风格很不清楚。无论如何,
%c不会给你一个字符串。 -
在您的 for 循环中,您将 int 与 char 进行比较,循环中与 toBS 的比较读取为输入“a”的 97。 print(toBS) 运行了 98 次,这是它在您发布的输出中显示的次数
标签: c