【问题标题】:Why does my Code not create a pyramid? Language: C为什么我的代码没有创建金字塔?语言:C
【发布时间】:2023-02-19 19:28:32
【问题描述】:

我想创建一个选定高度(从 1 到 8)的金字塔,中间有 2 个空格。所以对于高度为 3 的金字塔,它看起来像这样:

我使用了这段代码:

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


int main(void)
{
    // Ask for Height
    int height;
    do
    {
        height = get_int("Height: ");
    }
    while (height < 1 || height > 8);

    int counter = height;

    do
    {
        // Spaces Before Pyramid
        for (int i = 1; i < counter; i++)
        {
            printf(" ");
        }

        // First Blocks of Pyramid
        for (int j = counter; j == height; j++)
        {
            printf("#");
        }

        // Spaces between
        printf("  ");

        // Second Blocks of Pyramid
        for (int k = counter; k == height; k++)
        {
            printf("#");
        }

        // New Line
        printf("\n");

        counter--;
    }
    while (counter > 0);

}

但是输出总是第一行正确,其余都是空白。为什么?

【问题讨论】:

  • 反问:为什么不呢?
  • 当您在调试器中观察时,您看到执行采用哪条路径?哪里与您预期的不同?

标签: c


【解决方案1】:

您的第二个和第三个for 循环中的条件是错误的。 j==height应该是j&lt;heightk==height应该是k&lt;height

【讨论】:

    【解决方案2】:

    应修改第二个和第三个for 循环中的条件。

           for (int j = counter; j < height; j++)
            {
                printf("#");
            }
    
            // Spaces between
            printf("  ");
    
            // Second Blocks of Pyramid
            for (int k = counter; k < height; k++)
            {
                printf("#");
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多