我目前正在做 CS50 第一周的马里奥问题(不太舒服)。到目前为止,我可以打印金字塔的哈希值,但我无法用空格右对齐它。有人能够指出我哪里出了问题吗?预先非常感谢您。
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int hashes;
int space;
int height;
do
{
height = get_int("height: ");
}
while (height < 0 || height > 5);
{
for (int i = 0; i <= height; i++)
{
for (space = (height - 1); space <= 0; space++)
{
printf(" ");
}
for (hashes = 1; hashes <= i; hashes++)
{
printf("#");
}
printf("\n");
}
}
}
最佳答案
正如Antti所说,在你的“空间”循环中,在i的第一次迭代中(因此i = 0),height - 1
永远不会<或= 0(除非高度是设置为 1)。
如果高度设置为 5,则第一行 # 之前应打印多少个空格?是4吗?
那么,如果第一行 int Space = 0,height = 5,什么样的循环代码会得到 4 的结果?但是考虑一下 Space 的下一次迭代,如果 int Space = 1,Height = 5,什么循环代码可以获得结果 3?
for (space = 0; "this needs to to = 4" ; space++)
{
printf(" ");
}
for (space = 1; "this needs to to = 3" ; space++)
{
printf(" ");
}
“空格”的值在每次迭代时都会发生变化,您可以使用它吗?
关于c - 无法右对齐马里奥问题集的金字塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283901/