c - 在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 语言编码的第一周。我真的很难用这种语言表达我的逻辑。
先感谢您。
解决方案
除了来自莫斯科的@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
*********************
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
推荐阅读
- julia - 为什么 Julia (DifferentialEquations.jl) JumpProblem 在以后停止跳跃?
- angular - Angular中大项目列表的下拉菜单
- javascript - 从firebase实时数据库渲染FlatList React Native(expo cli)中的数据?
- python - python sympy - 如何处理表达式以保护它们免受特定评估
- c++ - 如何将 c++11 中的这个 stoi 使用转换为 atoi?
- git - 带有隐式变基的 git force pull
- tiff - 为 EXIF 找到 TIFF 标头中的字节顺序 0x49 0x01
- php - 我应该如何模拟这种关系?
- c# - 'await response.Content.ReadAsAsync 的 .net5 替代品是什么
()' - c++ - 整个范围内的 std::for_each 没有方便的重载?