【问题标题】:CS 50- Pset 1 Mario ProgramCS 50- Pset 1 马里奥程序
【发布时间】:2014-05-30 09:17:14
【问题描述】:

问题集要求我们使用哈希创建一个半金字塔。这是一个链接到它应该如何看待的图像 -

我明白了这个想法并编写了程序,直到打印空格(我已将其替换为“_”只是为了测试它的前半部分。

但是,当我尝试运行我的程序时,它并没有超出 do-while 循环。换句话说,它一直问我金字塔的高度,似乎根本没有运行 for 循环。我尝试了多种方法,但这个问题似乎仍然存在。

任何帮助将不胜感激!

下面是我的代码-

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

int main(void)

{
    int height; 

    do 
    {
        printf("Enter the height of the pyramid: ");
        height = GetInt(); 
    }
    while (height > 0 || height < 24); 

    for (int rows = 1; rows <= height, rows++) 
    {
        for (int spaces = height - rows; spaces > 0; spaces--)
        { 
            printf("_");
        }
    }
    return 0;
}

运行此程序会产生以下输出 -

Enter the height of the pyramid: 11
Enter the height of the pyramid: 1231
Enter the height of the pyramid: aawfaf
Retry: 12
Enter the height of the pyramid: 

【问题讨论】:

  • while (height &gt; 0 || height &lt; 24); 是导致问题的原因。永远正确。
  • 那个提示Retry是从哪里来的?
  • 如果您想知道如何使用单循环和每行输出作弊并通过合理、精确修改的字符串打印来做到这一点,see it live
  • 它是cs50.h 库@TomFenech 的一部分

标签: c loops debugging cs50


【解决方案1】:

您的 do/while 循环条件不正确 - 更改:

do {
    ...
} while (height > 0 || height < 24); 

到任一:

do {
    ...
} while (height <= 0 || height >= 24); 

或:

do {
    ...
} while (!(height > 0 && height < 24)); 

(无论您认为哪个更易读/更直观)。

【讨论】:

  • 您好,感谢您的回答。我刚刚对您建议的编辑背后的逻辑提出了一个简短的问题。如果我们希望高度在 1 到 23(含)之间,为什么 while 条件要告诉高度小于等于 0 大于等于 24?
  • @boametaphysica:我们正在测试高度是否无效,所以如果它是或 >= 24,那么它是无效,否则必须在1..23范围内,才有效。如果它更直观,您可以用其他方式表达这一点,例如while (height &lt;= 0 || height &gt;= 24) 等价于 while (height &lt; 1 || height &gt; 23)
  • 好的,我现在明白了。我希望循环中断,而不是让它像 do-while 循环那样继续,这就是为什么我需要一个会导致它中断的条件。再次非常感谢您!
【解决方案2】:

这样更简单吗

         for(int i=0;i<8;i++) {

             for(int j=0;j < (8-i); j++) 
             {

                 System.out.print(" ");
             }
            for(int k=0;k<=(i+1);k++)
            {

                System.out.print("#");
            }
            System.out.println();  
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多