创建“马里奥风格金字塔”

问题描述:

我正在浏览哈佛CS50在线课程,其中一个问题是使用空格和哈希创建“马里奥风格金字塔”。我已经解决了空间问题,但哈希值给我带来麻烦。下面的代码:创建“马里奥风格金字塔”

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

int main(void) 
{ 
    //get height between 1 and 23 
    int height; 
    do 
    { 
     printf("Please enter a height: "); 
     height = GetInt(); 
    } 
    while (height < 1 || height > 23); 

    //build pyramid 
    for (int i = 0; i < height ; i++) 
    { 
     //add spaces 
     for (int space = height - 1 - i; space >= 0; space--) 
      printf(" "); 

     //add hashtags 
     for (int hash = 2 + i; hash <= height; hash++) 
      printf("#"); 

     printf("\n"); 
    } 
} 

,当我在为5的高度终端运行它我得到这个:

 #### 
    ### 
    ## 
    # 
    <-- space here also 
时,我想这

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

任何反馈将不胜感激,谢谢

+3

如果你看看其他问题标签CS50,有无数与这同样的问题tussling - 也许在这些问答有助于解决问题。在搜索框中输入'[cs50] mario'。 –

+0

你让自己与对立的循环混淆。一个递减,一个递增。只需要两个增加的循环。第二个(哈希)基于第一个输出空间的数量。 –

+0

对于我自己我会使用一个单一的循环和一个局部常量初始化21个空格,然后是23个散列(所以不会让我粘贴它压缩空间)我会留给读者的细节:)这赢得了'你可以给你一个金字塔,但一个斜坡 – kdopen

只要用下面的代码尝试它:

int main(void) 
{ 
    int height; 
    printf("Please enter a height: "); 
    scanf("%d", &height); 

    //build pyramid 
    for (int i = height; i >= 1; i--) 
    { 
     //add spaces 
     for (int space = 1; space < i; space++) 
      printf(" "); 

     //add hashtags 
     for (int hash = height; hash >= i-1; hash--) 
      printf("#"); 

     printf("\n"); 
    } 
} 

height值,你得到所需的输出:

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

Working Fiddle


在你的代码,当i值在:

for (int i = 0; i < height ; i++) 
     ^^^^^^ 

其他回路的执行过程如下:

for (int space = height - 1 - i; space >= 0; space--) 
    printf(" "); 

这里,环路初始化空间= 4(当height是)并且循环条件有效,直到space >= 0,因此它将前4个字符打印为" "

,最后,当谈到这个循环:

for (int hash = 2 + i; hash <= height; hash++) 
    printf("#"); 

这里,环路初始化哈希= 2i是在第一循环,还记得吗?)和循环条件一直持续到hash <= height。所以,它打印的下一个4个字符作为"#"与上述条件评估为2,3,4,5中:

(int hash = 2; hash <= 5; hash++) 
      ^^^  ^^^ 

和代码的其余部分进行并产生输出为:

 #### 
    ### 
    ## 
    # 

如果你能够理解上面的逻辑,那么你就可以解码我的解决方案,以及:)

+5

您应该解释原始代码的错误以及您的答案如何解决问题。如果你只为他写答案,他不会学习。 – Barmar

+0

@Barmar,谢谢。希望这给出一个清晰的解释:) –

+1

一个非常有用的解释,谢谢! – roncook