【发布时间】:2016-12-22 00:52:41
【问题描述】:
我正在学习哈佛 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
当我想要这个时:
##
###
####
#####
######
任何反馈将不胜感激,谢谢
【问题讨论】:
-
如果您查看标记为 CS50 的其他问题,就会发现很多人都在为同样的问题争论不休——也许其中一个问答会有所帮助。在搜索框中输入
[cs50] mario。 -
您对相反的循环感到困惑。一个减少,一个增加。只需使用两个增加的循环即可。第二个(散列)基于第一个中输出的空格数。
-
对于我自己,我会使用一个循环和一个本地常量,初始化为 21 个空格,后跟 23 个哈希(所以不会让我粘贴它,因为它会压缩空格)我会留下详细信息读者 :) 那不会给你一个金字塔,而是一个坡道
-
跟着Jonathan Leffler的评论一起看this question