为什么我在 mario more cs50 pset1 中的代码为右侧金字塔打印了这么多哈希值

问题描述 投票:0回答:1

[编辑:代码已更正并添加了输出示例,使下面的旧注释无效。下次会更好。 ]

现在已经尝试了这个 cs50 mario more 问题一段时间了,但我似乎找不到解决方案,由于某种原因,正确的金字塔似乎打印出的内容比预期的要多,我的代码在下面,感谢我能得到的任何帮助。谢谢

#include <cs50.h>
#include <stdio.h>
int h;
int k;
int j;
int main(void)
{
    while (h<=0 || h>8)
    {
        h = get_int ("input pyramid height:");
    }

    for(j=0; j<h; j++)
    {
        for( k=0; k<=h; k++)
        {
            if (j+k<h)
                printf(" ");
            else
                printf("#");
        }
        printf("  ");

        for (int x=0; x<=j; x++)
        {
            for (int y=0; y<=x; y++)
                printf("#");
        }
        printf("\n");
    }
}

这就是我应该得到的高度= 4。(抱歉之前缺乏信息)

   #  #
  ##  ##
 ###  ###
####  ####

我得到的是这样的:(

   #  #
  ##  ###
 ###  ######
####  ##########
c cs50
1个回答
0
投票

过多的变量加减计数加在一起会让人头晕。无意义的单字母变量名会让读者“在 C 中迷失”。

简化问题,各个部分就应该各就各位。


不要透露太多,“检查问题”...

0th row: print n-0 spaces, the center '#' and LF
1st row: print n-1 spaces, 1x'#', the center again, and 1x'#' (and LF)
2nd row: print n-2 spaces, 2x'#', the center again, and 2x'#'...
3rd row: print n-3 spaces, 3x'#', the center again, and 3x'#'...

你看到这里形成了一个简单的图案吗?

现在垂直翻转行编号:

8th row: print (maybe) 8 spaces, then 1 '#'
7th row: print...
6th row: pr...

重新开始。打印一个仅在一行上的“金字塔”,然后将其扩展到两行。


上述内容是基于我对所需输出的错误理解。所需输出的“空心核心”现在使标题“马里奥”变得更加重要。

现在您已经发布了代码的“更整洁”版本,以及(经过一些修饰)所需/实际的输出,它是适当的(在SO上)来帮助解决您遇到的困难...

第二个内部

for()
循环应该是良好的第一个
for()
循环的镜像。
只需向下数

for( k=0; k<=h; k++) // ascending left
{
    if (j+k<h)
        printf(" ");
    else
        printf("#");
}

printf("  ");

for( k=h; k>0; k--) // descending right side
{
    if (j+k<h)
        printf(" ");
    else
        printf("#");
}

printf("\n");

这会输出不必要的空格,但代码很简单,对读者来说变得“显而易见”。

© www.soinside.com 2019 - 2024. All rights reserved.