本题要求实现一个函数,输出n行空心的数字金字塔。
函数接口定义:
void hollowPyramid( int n );
其中n
是用户传入的参数,为[1, 9]的正整数。要求函数按照如样例所示的格式打印出n
行空心的数字金字塔,请注意,最后一行的第一个数字前没有空格。
裁判测试程序样例:
#include <stdio.h>
void hollowPyramid ( int n );
int main()
{
int n;
scanf("%d", &n);
hollowPyramid ( n );
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
5
输出样例:
1
2 2
3 3
4 4
555555555
结果:
代码:
void hollowPyramid(int n)
{
int i, j, k, temp = 1;
//打印每一行
for (i = 1; i <= n; i++)
{
// 打印左侧空格
for (j = 1; j <= n - i; j++)
{
printf(" ");
}
// 打印数字以及中间空格
for (k = 1; k <= temp; k++)
{
if (k == 1 || k == temp || i == n)
{
printf("%d", i);
}
else
{
printf(" ");
}
}
temp += 2;
printf("\n");
}
}