我目前正在学习在线类(class) CS50。目标是创建一组在马里奥第一层中找到的楼梯,就像下面由主题标签制成的楼梯一样。我已经能够打印用户输入的高度,但我的循环不会缩进任何标签来制作楼梯。有任何想法吗?
它应该是什么样子
##
###
####
#####
我的样子
#
#
#
#
代码:
#include <stdio.h>
int main(void)
{
int line = 0;
int blockHeight = blockHeight - 1;
int space = blockHeight - 1;
int hashes = 2;
do
{
printf("please give me a number between the range of 1 and 23:\n");
scanf("%i", &blockHeight);
}
while (blockHeight >= 1 != blockHeight <= 23);
{
printf("thanks for the correct answer!\n");
}
printf("\n\n\n");
for (int i = 0; i < blockHeight; i++)
{
for (int j = 0; j < space; j++)
{
printf(" ");
space--;
break;
}
for (int k = 0; k < hashes; k++)
{
printf("#");
hashes++;
break;
}
for (int z = 0; z < blockHeight; z++)
{
printf("\n");
break;
}
}
}
最佳答案
1.
int blockHeight = blockHeight - 1;
int space = blockHeight - 1;
这是初始化变量的错误方法。 改成
int blockHeight, space;
在获取 blockHeight
的值后,您可以分配 space = blockHeight - 1;
(在 do-while 循环之后)
2.
do
{
printf("please give me a number between the range of 1 and 23:\n");
scanf("%i", &blockHeight);
}
while (blockHeight < 1 || blockHeight > 23); // write `||` instead of `!=`
printf("thanks for the correct answer!\n");
它将运行 do
直到满足条件。满足条件后,它将打印 while
后写入的消息。
3.
for (int j = 0; j < space; j++)
{
printf(" ");
space--;
break;
}
将此更改为
for (int j = 0; j < space; j++)
{
printf(" ");
}
space--;
因为你在你的循环中写了 break;
所以 for 循环将只工作一次并且它会退出循环。
4.
for (int k = 0; k < hashes; k++)
{
printf("#");
hashes++;
break;
}
将此更改为
for (int k = 0; k < hashes; k++)
{
printf("#");
}
hashes++;
因为 break;
它会打印一次 #
并退出循环。
5.
for (int z = 0; z < blockHeight; z++)
{
printf("\n");
break;
}
不需要写这个for循环。一行就够了。将此更改为
printf("\n");
6.
int main(void)
{
////
// your code
////
return 0; // write this line at the end
}
关于c - 循环循环,但仍然难以理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33750388/