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

标签 c cs50

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

#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 failed;是if语句的一部分;第二个实际上是一个单独的实体,尽管它是缩进的,就好像它是 if 语句的一部分一样。 (有关此示例所基于的 Apple 代码中实际错误的详细信息,请参阅此内容:https://dwheeler.com/essays/apple-goto-fail.html)

所以请正确使用大括号并正确缩进,以便代码执行其看起来正在执行的操作。

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

#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):

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

关于CS50 马里奥(更舒适)错误。为什么我的金字塔没有正确对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60159458/

相关文章:

c - strchr()中多字符字符常量错误

c - 为什么 sizeof(x++) 不增加 x?

C——基本结构问题

c - 陷入 Vigenere 加密程序的最后部分

c - 为什么我在 C 语言中收到警告 'Segmentation fault, core dumped'

c - 如何定位段错误的根源? (CS50 : recover.c)

c - 如何在给定程序中打印评论?

c - 我想连续从COM端口接收数据,同时想写入文件

c - 使用 native Win32 读取 'C' 中的文本文件 (Unicode)

c - 如何使我的哈希算法更快