【问题标题】:Recursive Function of Characters To Binary (ASCII)字符到二进制 (ASCII) 的递归函数
【发布时间】:2014-11-26 19:23:51
【问题描述】:

我在院子里以 2 美元的价格买了一本编程书,因为我一直想学习如何编码,但没有钱和资源上学。我已经很好地完成了前几章,但我也有解决我正在研究的问题的方法。但是当他们开始列出问题时,该章在章节摘要之后缺少一些页面。我想知道你们是否可以帮助我。

这就是问题所在。注意:需要使用递归函数。

#include <stdio.h>
#include <stdlib.h>

void binaryPrinter(int value, int *numberOfOnes);
void print(char c);

//You do not need to modify any code in main
int main()
{
    char value;
    int result = 1;

    while(result != EOF)
    {
        result = scanf("%c",&value);

        if(result != EOF && value != '\n')
        {
            print(value);
        }
    }
}

//@hint: This is called from main, this function calls binaryPrinter
void print(char c)
{

}

//@hint: this function is only called from print
void binaryPrinter(int value, int *numberOfOnes)
{

}

【问题讨论】:

  • 您是否要将此代码更改为递归?
  • 这本书说我只需要完成这两个函数,以便将用户输入打印成二进制,但是是的,我相信其中一个函数应该自己调用其他函数。
  • 从另一个函数调用一个函数不是递归。可以(并且更容易)使用 1 个函数来执行此操作而无需递归。
  • 那么什么是递归函数?

标签: c function recursion binary ascii


【解决方案1】:
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);
    }
}

【讨论】:

  • #include &lt;limits.h&gt; 丢失。
  • 您的代码中缺少它(您使用 CHAR_BIT 而不包括相应的标头)
  • 虽然我知道它包含在limits.h中。我不知道是否允许添加写入它。幸运的是,它是从我的系统上的stdlib.h 读取的。
  • 它对其他人有用,因为你给了我一个便条。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 2019-05-06
  • 2022-11-14
  • 2012-08-02
  • 2016-12-21
  • 1970-01-01
  • 2015-01-15
相关资源
最近更新 更多