CS50 马里奥(更舒适)错误。为什么我的金字塔没有正确对齐?

CS50 Mario (More Comfortable) Error. why are my Pyramids not Aligning properly?

我的代码有什么问题?当我 运行 它们单独时,金字塔正确对齐,但在我删除 // 符号以 运行 它们在一起后,我的金字塔搞砸了。请问我做错了什么?

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int H;
    //Ask for Height of Pyramid
    do {
        H = get_int("Height Please: ");

    } while (H<=0 || H > 8);
    for (int x=0;  x < H; x++)
        {
        // Create left Aligned Pyramid
           for (int y = 0; y < H; y++)
                   if (x + y < H - 1)
                      printf(" "); 
                  else 
                      printf("#");
                      printf("\n");

        // Create Right Aligned Pyramid
           for (int y = 0; y < H; y++)
                if (x-y>=0) 

                       printf(" "); //Space in Between both Pyramids
                       printf("#");

                 else 
                      printf(" ");                  
                     printf("\n");          
    }

}

让我们从第一个问题开始:您确实应该使用花括号来显式封装您的循环和 if-else 语句,否则只有后续语句是其中的一部分。例如:

if (condition)
    goto fail;
    goto fail;

只有第一个 goto fail; 是 if 语句的一部分;第二个实际上是一个单独的实体,即使它被缩进,就好像它是 if 语句的一部分一样。 (有关此示例基于的 Apple 代码中真实错误的详细信息,请参阅此文件:https://dwheeler.com/essays/apple-goto-fail.html

所以请正确使用大括号并正确缩进,这样代码就可以按照它看起来的样子去做。

其次,您在打印第一个金字塔和第二个金字塔的逻辑之间打印换行符,因此它们永远不会并排存在。该换行符是您应该插入额外 space 字符的位置,而不是您的第二个金字塔的逻辑。

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int H;
    //Ask for Height of Pyramid
    do {
        H = get_int("Height Please: ");

    } while (H<=0 || H > 8);

    for(int x = 0; x < H; x++) {
        // Create left Aligned Pyramid
        for(int y = 0; y < H; y++) {
            if (x + y < H - 1) {
                printf(" ");
            }
            else {
                printf("#");
            }
        }

        printf(" ");    // With the curly braces and indentation fixed, we can clearly see this is not part of the logic of the first pyramid, but rather between the first and second pyramids where a space should be

        // Create Right Aligned Pyramid
        for(int y = 0; y < H; y++) {
            if (x - y >= 0) {
                printf("#");
                // remove the space character that did not belong here and was causing compile errors when you failed to use curly braces
            }
            else {
                printf(" ");
            }
        }

        printf("\n");   // Much easier to see where this logic comes into play with curly braces and indentation fixed.

    }
}

示例输出(硬编码 H=4):

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