C编程: A pyramid with asterisks

标签 c function printing

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

这应该是这样的输出:

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

我的代码:

#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程序员初学者。

最佳答案

输出金字塔(居中)的另一种方法是使用 printf字段宽度修饰符格式字符串 em>padding 而不是填充字符本身。然后,您可以简单地循环输出每行所需的字符数(每行增加 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
         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

关于C编程: A pyramid with asterisks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52810887/

相关文章:

c - ANSI C 警告 : assignment from incompatible pointer type

c - ncurses 中的菜单分隔符

java - 调用批处理运行jar的方法

Python 函数自省(introspection) : what members of a class passed as argument are mentioned inside it?

powershell - 为什么 powershell(ise) 有时会打印出我执行的代码?

java - 如何在for循环中向空字符串添加值?

Firefox 仅打印第一页

编译器说 pow 是未定义的,即使我正在链接 -lm,但编译时

c - break in side for loop - 在 break 语句之后不在 for 循环之外打印任何内容

c - 释放函数中分配的内存