0

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

在此处输入图像描述

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

但是,当我尝试运行我的程序时,它并没有超出 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: 
4

2 回答 2

3

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

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

到:

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

或者:

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

(无论您认为哪个更具可读性/直观性)。

于 2014-05-30T09:21:08.883 回答
-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();  
        }
于 2014-07-25T13:06:42.963 回答