这段代码的目标是打印金字塔。首先,我打印一定数量的空格,然后打印一些星星,最终形成一个金字塔。
例如,要首先打印 5 的金字塔,它将在 4 个空格后打印一颗星,然后将更改开始和结束变量,因此新的开始将是 3,新的结束将是 6,它将打印 3 个星星。
#include <stdio.h>
#include <stdlib.h>
void printSpaces(int num){
int i;
for(i=0; i<num;i++)
{
printf(" ");
}
}
void pyramid(int n){
int start=n,end=n+1;
int k;
while(start>0 && end<2*n)
{
printSpaces(start);
for (k=start; k<end;k++)
{
printf("*");
}
printf("\n");
start=n-1;
end=n+1;
}
}
int main(void) {
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
pyramid(5);
return 0;
}
它似乎唯一做的事情就是一遍又一遍地打印一行 2 颗星。
最佳答案
您将 start 设置为 n-1,但 n 的值永远不会改变。这意味着 start 将连续设置为相同的值 n-1(4)。与 end 相同,你的循环永远不会终止。
void pyramid(int n){
int start=n,end=n+1;
int k;
while(start>0 && end<2*n)
{
printSpaces(start);
for (k=start; k<end;k++)
{
printf("*");
}
printf("\n");
start=n-1;
end=n+1;
}
}
此外,第一次调用时,k 将为 4,end 将为 6,因此有两颗星。
关于c - 我不明白为什么这不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30814429/