需要用数字和星星之间的空格来建立一个金字塔
问题描述:
1
**
2 3
*** ****
金字塔应该看起来像这样使用指定的行数。我应该使用for循环。不过,我真的很困惑如何在数字和星星之间添加适当的空间。此外,如何获取每行显示的正确数字,以及使用什么条件来停止适当数量的数字。这是我到目前为止:需要用数字和星星之间的空格来建立一个金字塔
{
int userinput, rows, space, stspace, stars, num;
//int startingnum;
int i;
printf("Enter the number of rows: ");
scanf("%d",&userinput);
printf("\n");
for(rows=1; rows<=userinput; rows++)
//printf("\n");
{
printf("\n");
//for(i=1; i <= rows; i++)
//{
//startingnum += i;
//}
if(rows%2!=0)
{
for(space=1; space<=(userinput)/(rows+1); space++)
printf("-");
{
for(num=1; num<=rows; num++)
printf("%d",num);
}
}
else
{
for(stspace=1; stspace<=(userinput)*(rows); stspace++)
printf("-");
{
for(stars=num+1; stars<=num+rows+1;stars++)
printf("*");
}
}
}
}
任何帮助非常感谢!
答
这样
#include <stdio.h>
#include <string.h>
int main(void){
int rows;
printf("Enter the number of rows: ");fflush(stdout);
scanf("%d", &rows);
printf("\n");
#if 0
Draw the following when rows is 2
[ ] represents one element. [] is for easy understanding for a element
[ ][ 1 ]
[ ][ ** ]
[ 2 ][ ][ 3 ]
[*** ][ ][****]
#endif
int last_number = rows * (rows + 1)/2;
int element_width = last_number + 1;
char blank_element[element_width +1];//+1 for NUL
char stars_element[element_width +1];
char work_element[element_width +1];
char str_num[element_width +1];
void repeatStringOutput(const char *str, int times);
//make blank element
memset(blank_element, ' ', element_width);
blank_element[element_width] = 0;
//initialize stars element
strcpy(stars_element, "*");
int num = 1;
for(int r = 1; r <= rows; ++r){
//print pre-blank-element
repeatStringOutput(blank_element, rows - r);
for(int c = 0; c < r; ++c){
int len = sprintf(str_num, "%d", num + c);
if(c)//print blank element between stars element
fputs(blank_element, stdout);
strcpy(work_element, blank_element);//fill spaces
memcpy(work_element + (element_width - len)/2, str_num, len);//centering
fputs(work_element, stdout);
}
puts("");
repeatStringOutput(blank_element, rows - r);
for(int c = 0; c < r; ++c){
strcpy(stars_element + num++, "*");
if(c)
fputs(blank_element, stdout);
strcpy(work_element, blank_element);
memcpy(work_element + (element_width - num)/2, stars_element, num);
fputs(work_element, stdout);
}
puts("");
}
}
void repeatStringOutput(const char *str, int times){
while(times--)
fputs(str, stdout);
}
+0
[DEMO](http://ideone.com/zo3IK2) – BLUEPIXY
空间声明,代码的格式很奇怪,当我在,所以我可能会不小心删除了声明,当我固定它粘贴它。我会编辑。 –
提示:last_number = rows *(rows + 1)/ 2. element_max_width = last_number + 1. – BLUEPIXY