c - 我不明白为什么这不起作用

标签 c

这段代码的目标是打印金字塔。首先,我打印一定数量的空格,然后打印一些星星,最终形成一个金字塔。

例如,要首先打印 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/

相关文章:

c - void * 作为函数参数

c - RSA_generate_key() openssl : exp argument

c - C中递归的二维数组

c - OpenMP omp fork 2 个线程比 fork 4 个线程快得多,为什么?

c - 是否可以在 C 中创建一个 "variable" header 保护名称?

c++ - 如何使用 zlib.h 解压缩 m MYSQL_RES 中的 COMPRESSED BLOB,而不在 mysql 查询中使用 UNCOMPRESS

c - 如何编译这段代码?

c - 迷失在递归中-如何反向打印用户输入的单个字符并将它们相乘

C 使用常量声明二维数组

c - 我的环境中的 realpath() 不喜欢 NULL 作为第二个参数?