c - 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 程序员初学者。
解决方案
输出金字塔(居中)的另一种方法是使用字段宽度修饰符作为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
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
推荐阅读
- mysql - 使用命令提示符安装 mysql 时出现问题,对于 django
- zurb-foundation - 在 Mac 上安装 Foundation-cli 的问题
- sql - 在 oracle 中快速执行什么语句,删除+插入或插入 ID 不在列表中。?
- apache-kafka-streams - 合并两个时间窗口的最佳模式是什么
- python - Matplotlib:从二进制数据填充
- html - 如何显示位置在通过 XMLHttpRequest 访问的 JSON 文件中的图像?
- java - Java Map computeIfAbsent 问题
- laravel - 如何在 Laravel 中直接访问数组或对象?
- git - 如果我意外提交特定文件,需要 git 拒绝提交
- sql - SQL Scalar 函数从存储过程运行很长时间