首页 > 解决方案 > 在C中递归绘制沙漏

问题描述

我需要在 C 中递归地绘制沙漏。我需要有 1 个辅助函数加上实际函数。以下是函数签名: void helper(unsigned int height, unsigned int offset) void real(unsigned int height)

其中height描述了要绘制的行数,offset是每行开头的空格数。对于每一行,星星的数量应该减少 2,偏移量应该增加 1,高度应该减少 1,直到到达沙漏的中间。之后,高度应继续减少,但星数应增加 2,偏移量应减少 1。如果输入高度是偶数,则第一行应具有高度 - 1 颗星。此外,中间应该有两排只有 1 颗星。如果输入高度是奇数,那么第一行应该有高度星。

Ex) height = 6
*****
 ***
  *
  *
 ***
***** 

Ex) height = 5
*****
 ***
  *
 ***
*****

我必须使用递归,不允许循环。

这是我的辅助功能。我无法弄清楚主要功能。

void draw_hourglass_rec_helper(unsigned int height, unsigned int offset)
 {

  if (height == 0) {
    printf("\n");
  } else if (offset == 0) {
    printf("*");
    draw_hourglass_rec_helper(height-1, 0);
  } else {
    printf(" ");
    draw_hourglass_rec_helper(height, offset-1);
  }
 }

最佳尝试:

void draw_hourglass_rec(unsigned int height)
{
  if(height < 1)
  {
  return;
  }
 {
   draw_hourglass_rec_helper(height, ((-0.5 * height) + (9.0/2.0)));
   draw_hourglass_rec(height-2);
 }

}

印刷 :

**********
********
 ******
  ****
   **

对于 draw_hourglass_rec(10) 几个问题 1) 我不能打印沙漏的下半部分 2) 星星的数量应该总是奇数 3) 我不知道如何表达应该有 2 行的偶数输入情况每个 1 星 4) 如果我在奇数高度使用此代码,我会陷入无限循环。

这是我用 C 语言编码的第一周。我真的很难用这种语言表达我的逻辑。

先感谢您。

标签: cfunctionrecursiondefinition

解决方案


除了来自莫斯科的@Vlad提供的选择之外,您还可以采用另一种方法,它使用相同的辅助函数进行递归,但是将初始高度设置为负,并且当高度大于输入的原始值时递归结束,例如

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

void hghelper (int h, int current)
{
    if (current > h)
        return;

    int ac = abs(current);

    if (ac == 1)
        current = 1;

    if (ac != 0) {
        int stars = ac;
        int indent = (h - stars) / 2;

        while (indent--)
            putchar (' ');
        while (stars--)
            putchar ('*');
        putchar ('\n');
    }

    hghelper (h, current + 2);
}

void hourglass (int h)
{
    int negh = -h;

    hghelper (h, negh);
}

int main (int argc, char **argv) {

    int height;

    if (argc > 1) {
        if (sscanf (argv[1], "%d", &height) != 1 || height < 0)
            return 1;
    }
    else
        height = 5;

    hourglass (height);
}

示例使用/输出

请注意,对于此算法,基数(宽度)始终具有与高度相同的星数。您可以根据需要进行调整。

默认height = 5

$ ./bin/hourglass_recursive
*****
 ***
  *
 ***
*****

height = 6

$ ./bin/hourglass_recursive 6
******
 ****
  **
  **
 ****
******

height = 7

$ ./bin/hourglass_recursive 7
*******
 *****
  ***
   *
  ***
 *****
*******

height = 21

$ ./bin/hourglass_recursive 21
*********************
 *******************
  *****************
   ***************
    *************
     ***********
      *********
       *******
        *****
         ***
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
*********************

推荐阅读