创建“马里奥风格金字塔". [英] Creating a "Mario Style Pyramid"
问题描述
我正在学习哈佛CS50在线课程,问题之一是使用空格和哈希值创建马里奥风格金字塔".我已经解决了空间,但是散列给我带来了麻烦.这是代码:
I'm going through the Harvard CS50 online course and one of the problems is to create a "mario style pyramid" using spaces and hashes. I've got the spaces solved but the hashes are giving me trouble. Here's the code:
#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的终端中运行它时,我会得到这个信息:
When i run it in the terminal with a height of 5 i'm getting this:
####
###
##
#
<-- space here also
当我想要这个时:
##
###
####
#####
######
任何反馈将不胜感激,谢谢
Any feedback would be appreciated, thanks
推荐答案
只需尝试以下代码:
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
的值为 5 时,您将获得所需的输出:
when the value of height
is 5, you get the desired output:
##
###
####
#####
######
请参见 工作小提琴 .
See the Working Fiddle.
在您的代码中,当i
的值为 0 时:
In your code, when the value of i
is 0 in:
for (int i = 0; i < height ; i++)
^^^^^^
其他循环执行如下:
for (int space = height - 1 - i; space >= 0; space--)
printf(" ");
在这里,循环初始化 space = 4 (当height
为 5 时),循环条件一直有效到space >= 0
,因此它将打印前4个字符为" "
.
here, the loop initializes space = 4 (when height
is 5) and the loop condition is valid till space >= 0
, so it prints the first 4 characters as " "
.
最后,涉及到此循环:
for (int hash = 2 + i; hash <= height; hash++)
printf("#");
在这里,循环初始化 hash = 2 (i
在第一个循环中为 0 ,还记得吗?)条件持续到hash <= height
.因此,由于上述条件在以下条件中计算为 2,3,4,5
,因此它将下一个4个字符打印为"#"
:
here, the loop initializes hash = 2 (i
was 0 in the first loop, remember that?) and the loop conditions continues till hash <= height
. So, it prints the next 4 characters as "#"
as the above condition evaluates to 2,3,4,5
in:
(int hash = 2; hash <= 5; hash++)
^^^ ^^^
其余代码继续进行并产生如下输出:
and the rest of the code carries on and produces the output as:
####
###
##
#
如果您能够理解上述逻辑,那么您也可以解码我的解决方案:)
If you are able to understand the above logic, then you'd be able to decode my solution as well :)
这篇关于创建“马里奥风格金字塔".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!