-
#include<stdio.h>
-
-
-
int diamond(int count,char ch){
-
-
if(count <=0){
-
printf("Count is error\n");
-
return 0;
-
}else{
-
int i;
-
int j;
-
//输出字符
-
int k;
-
int m;
-
int d = count;
-
for(k=1;k<=count;k++){
-
-
for(i=d;i>1;i--){
-
printf(" ");
-
}
-
for(m=1;m<=(2*k-1);m++){
-
printf("%c",ch);
-
}
-
printf("\n");
-
d = d - 1;
-
}
-
j = 1;
-
for(k=(count-1);k>=1;k--){
-
-
for(i=1;i<=j;i++){
-
printf(" ");
-
}
-
for(m=(2*k - 1);m>=1;m--){
-
printf("%c",ch);
-
}
-
printf("\n");
-
j= j + 1;
-
}
-
-
-
}
-
return 0;
-
-
}
-
-
-
int main(void){
-
-
diamond(5,'*');
-
-
return 0;
- }
改进的代码:
-
int diamond(int count,char ch){
-
int i, j;
-
int line = 0;
-
int space_num = 0;
-
-
if((line = 2*count - 1) <=0){
-
printf("Count is error\n");
-
return -1;
-
}
-
-
for(i=1; i<=line; i++) {
-
space_num = (i/count)? i%count:(count-i%count);
-
-
for(j=0; j<line-space_num; j++)
-
printf("%c",(j < space_num)? 32:ch);
-
printf("\n");
-
}
-
-
return 0;
-
}
换一种思路:
-
int diamond(int count,char ch){
-
int row, col;
-
int n;
-
-
if((n = count - 1) < 0) {
-
printf("Count is error\n");
-
return -1;
-
}
-
-
for (row = -n; row <= n; row++) {
-
for (col = -n; col <= n; col++)
-
printf("%c", (fabs(row) + fabs(col) <= n)? ch:32); //<=改成==可以打印空心菱形
-
-
printf("\n");
-
}
-
-
return 0;
- }