显示倒金字塔的星号

时间:2010-03-31 19:23:49

标签: c io

我帮助我的程序。我需要创建一个倒金字塔的星星,其行数取决于用户键的星数,但我已经完成了它,因此它没有给出倒金字塔,它给出了一个规则的金字塔。

#include <stdio.h>
#include <conio.h>
void printchars(int no_star, char space);
int getNo_of_rows(void);
int main(void)
{
    int numrows, rownum;
    rownum=0;
    numrows=getNo_of_rows();
    for(rownum=0;rownum<=numrows;rownum++)
    {
        printchars(numrows-rownum, ' ');
        printchars((2*rownum-1), '*');
        printf("\n");
    }
    _getche();
    return 0;
}

void printchars(int no_star, char space)
{
    int cnt;
    for(cnt=0;cnt<no_star;cnt++)
    {
        printf("%c",space);
    }
}

int getNo_of_rows(void)
{
    int no_star;
    printf("\n Please enter the number of stars you want to print\n");

    scanf("%d",&no_star);
    while(no_star<1)
    {
        printf("\n number incorrect, please enter correct number");
        scanf("%d",&no_star);

    }
    return no_star;
}

2 个答案:

答案 0 :(得分:4)

你的线条显示的顺序与你想要的相反,对吧?所以你要做的是查看打印行的代码:

 for(rownum=0;rownum<=numrows;rownum++)
 {
  printchars(numrows-rownum, ' ');
  printchars((2*rownum-1), '*');
  printf("\n");
 }

并弄清楚如何让它倒退。上面的代码调用printchars,其2*rownum-1星的行数最多为2*numrows-1星,因为rownum0开始,最多可计入numrows。< / p>

你怎么能改变这一点,以便你rownumnumrows开始并倒数到零呢?

答案 1 :(得分:2)

尝试一步一步手动完成代码。

拿出一些方格纸。

说你的输入是5.只是按照你的清单中的内容(没有执行)它会说它会输出到屏幕上?把它画在方格纸上。

看看你是否能发现错误。

一些未经请求的建议:

  • 使用numrows作为输入,使用rownum作为索引会让人感到困惑(这是错误的来源)。考虑使您的索引变量与输入更加不同(可能是rn)。
  • 考虑与缩写保持一致。您使用no_No_of_num作为“number of”的缩写。