首页 > 解决方案 > C 编程:带星号的金字塔

问题描述

我做对了什么?我正在尝试学习一个功能。

这应该是这样的输出:

   *
  ***
 *****
*******

我的代码:

#include <stdio.h>
#include <stdlib.h>

void pyramid (int n)
{
    int width = 0;

    if ( n )
    {
        ++width;
        pyramid( f, n - 1 );

        for ( unsigned int i = 0; i < 2 * n - 1; i++ )
        {
            fprintf( f, "%*c", i == 0 ? width : 1, '*' );
        }

        fputc( '\n', f );
        --width;
    }
}

int main (int argc, char *argv[])
{
    if (argc < 2)
    {
        printf ("usage: h4 <number>\n");
        return 1;
    }
    pyramid (atoi (argv[1]));

    return 0;
}

输出:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

Traceback (most recent call last):
  File "python", line 4
    void pyramid (int n) {
               ^
SyntaxError: invalid syntax

为什么会出现这个问题?请帮我解释一下。谢谢你。我是聋 C 程序员初学者。

标签: cfunctionprinting

解决方案


输出金字塔(居中)的另一种方法是使用字段宽度修饰符作为printf 格式字符串填充而不是填充字符本身。然后你可以简单地循环输出每行所需的字符数(每行增加2,例如1, 3, 5, ...)。

例如,将输出的行数作为程序的第一个参数,(或者4如果没有给出参数,则默认使用),您可以执行类似以下的操作:

#include <stdio.h>
#include <stdlib.h>

#define FILL '*'

void pyramid (int n)
{
    if (n < 1)              /* validate positive value */
        return;

    int l = 1,              /* initial length of fill chars */
        max = n * 2 - 1,    /* max number of fill chars */
        pad = max / 2;      /* initial padding to center */

    for (int i = 0; i < n; i++) {       /* loop for each line */
        if (pad)                        /* if pad remains */
            printf ("%*s", pad--, " "); /* output pad spaces */
        for (int j = 0; j < l; j++)     /* output fill chars */
            putchar (FILL);
        putchar ('\n');                 /* output newline */
        l += 2;             /* increment fill by 2 */
    }
}

int main (int argc, char **argv) {

    int n = argc > 1 ? (int)strtol (argv[1], NULL, 0) : 4;

    pyramid (n);

    return 0;
}

注意:您可以unsigned在整个过程中使用类型来确保正值,或者您可以简单地验证您有正值。您还应该包含errno.h并验证转换,但如果没有提供数字strtol,它将返回)0

它还有助于#define在代码顶部填充字符,因此如果您想要另一个字符,您可以方便地进行更改。它可以防止在以后挖掘你的函数来找到常量。

示例使用/输出

$ ./bin/pyramidtop 1
*

$ ./bin/pyramidtop 5
    *
   ***
  *****
 *******
*********

$ ./bin/pyramidtop 10
         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

推荐阅读