我做对了什么?我正在尝试学习一个函数。
这应该是这样的输出:
*
***
*****
*******
我的代码:
#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/