刚开始自学编程,这么一个简单的题目居然做了很久,果然书看千遍不如手打一遍T_T
#include <stdio.h>
#include <stdlib.h>
void space_print(int i);
void character_print(int i,char ch);
void pro_print(int i);
void con_print(int i);
int n ;char ch;
//n是输入的总字符数
int main(void)
{
int print_character(int n,char ch);
scanf("%d %c",&n,&ch);
print_character(n,ch);
return 0;
}
int print_character(int n ,char ch){
int i,row,small,last_c;
//row是半个沙漏的行数
if (n <= 0)
{
return -1;
}
else{
small=0 ;i=0;
while (small<n){
small=2*i*i+4*i+1;
i+=1;
}
row=i-1;
last_c=n-2*(row-1)*(row-1)-4*(row-1)-1;
return 0;
}
if(1==n) last_c=0;
pro_print(row);
space_print(row-1);
character_print(1,ch);
printf("\n");
con_print(row);
printf("%d",last_c);
//printf("\ni is %d and row is %d and last_c is %d",i,row,last_c);
}
//打印从多到少的沙漏形状直到中间
void pro_print(int i){
for (int j = 0; j < (i - 1); ++j)
{
space_print(j);
character_print(2*(i-j)-1,ch);
printf("\n");
}
}
//打印从少到多的沙漏形状直到底部
void con_print(int i){
int j;
for(j=0;j<(i-1);j++){
space_print(i-j-2);
character_print(2*j+3,ch);
printf("\n");
}
}
//打印指定数量的空格用于形成沙漏的形状
void space_print(int i){
for (int j = 0; j < i; ++j)
{
printf(" ");
}
}
//打印指定数量的指定字符
void character_print(int i,char ch){
int j;
for (int j = 0; j < i; ++j)
{
printf("%c",ch);
}
}
有个问题:当n=1的时候剩余字符数会有错误,为了通过测试强行加了一句
if(1==n) last_c=0;
菜的不忍直视
网友评论