我已经开始CS50x习题集1;但是我的程序似乎在输入高度数字后停止。
即该程序将要求输入一个 8 到 23 之间的数字(重复直到它获得正确的输入),一旦我这样做,代码就会停止。
我做错了什么?
下面是我写的代码。非常感谢所有帮助,因为我在这里查看了 S.E. 上的各种问题。但没有解决这个问题。
include stdio.h
include cs50.h
int main (void)
{
printf("ok lets make a pyramid :)\n");
// height = x
int x;
// spaces = z
int z;
// hashes = a
int a;
// Get correct number for height
do
{
printf("Give me a positive number between 8 and 23 for the height of the pyramid\n");
x = GetInt();
}
while (x < 8 || x > 23);
// Build the phantom pyramid
for (int q = 0; q == x; q++)
{
// Spaces
for (z = x - 1; z == 0 ; z--)
{
printf(" ");
}
// Hashtags
for (a = 1; a == q; a++)
{
printf("#\n");
}
}}
最佳答案
除此之外你的 #include
语法错误( #include <stdio.h>
),你的基本问题在这里,你的程序退出而不打印任何东西的原因是主要的 for
永远不会进入循环。 C for
循环在控制表达式为真时执行,直到 is 为真。你有:
for (int q = 0; q == x; q++){ ... }
自 q == x
评估为 0
(假),因为 q
是0
和 x
在 8 和 23 之间,这个循环永远不会执行,程序退出。你的每个循环都有这个问题。你可以修复它:
for (int q = 0; q < x; q++)
{
// Spaces
for (z = x - 1; z > 0 ; z--)
{
printf(" ");
}
// Hashtags
for (a = 0; a <= q; a++)
{
printf("#");
}
printf("\n");
}
这里,注意在循环的第一遍中,q
是 0,所以 a
必须从 0 开始才能在第一行打印单个散列。此外,在循环完成打印行之前,不会打印换行符。这些更改为高度 8 提供了此输出:
#
##
###
####
#####
######
#######
########
我不确定这是否是您想要的输出。左边的间距与金字塔的高度有关。如果你想要左边的金字塔台阶,你可以更改关联的for
声明:
for (z = x - 1; z > q ; z--)
但我的印象是马里奥金字塔的左边是台阶,顶行有两个哈希值。您可以修改循环来执行此操作,但这是一个不同的循环。您不需要变量 a
,而不是想 z
作为“空格”,将其视为代表行位置:
for (int q = x; q > 0; q--) {
// print spaces at beginning of line
for (z = 1; z < q; z++) {
printf(" ");
}
// print hashes at end of line
for ( ; z < x + 2; z++) {
printf("#");
}
// print newline when finished printing line
printf("\n");
}
新循环给出高度为 8 的输出:
##
###
####
#####
######
#######
########
#########
关于cs50x马里奥金字塔不画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41081098/