Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4024308
  • 博文数量: 366
  • 博客积分: 9916
  • 博客等级: 中将
  • 技术积分: 7195
  • 用 户 组: 普通用户
  • 注册时间: 2011-05-29 23:27
个人简介

简单!

文章分类

全部博文(366)

文章存档

2013年(51)

2012年(269)

2011年(46)

分类: C/C++

2013-04-20 12:43:56

一般逻辑性代码:
  1. #include<stdio.h>


  2. int diamond(int count,char ch){

  3.         if(count <=0){
  4.                 printf("Count is error\n");
  5.                 return 0;
  6.         }else{
  7.                 int i;
  8.                 int j;
  9.                 //输出字符
  10.                 int k;
  11.                 int m;
  12.                 int d = count;
  13.                 for(k=1;k<=count;k++){

  14.                         for(i=d;i>1;i--){
  15.                                 printf(" ");
  16.                         }
  17.                         for(m=1;m<=(2*k-1);m++){
  18.                                 printf("%c",ch);
  19.                         }
  20.                         printf("\n");
  21.                         d = d - 1;
  22.                 }
  23.                 j = 1;
  24.                 for(k=(count-1);k>=1;k--){

  25.                         for(i=1;i<=j;i++){
  26.                                 printf(" ");
  27.                         }
  28.                         for(m=(2*k - 1);m>=1;m--){
  29.                                 printf("%c",ch);
  30.                         }
  31.                         printf("\n");
  32.                         j= j + 1;
  33.                 }


  34.         }
  35.         return 0;

  36. }


  37. int main(void){

  38.         diamond(5,'*');

  39.         return 0;
  40. }

改进的代码:
  1. int diamond(int count,char ch){
  2.     int i, j;
  3.     int line = 0;
  4.     int space_num = 0;

  5.     if((line = 2*count - 1) <=0){
  6.         printf("Count is error\n");
  7.         return -1;
  8.     }
  9.     
  10.     for(i=1; i<=line; i++) {
  11.         space_num = (i/count)? i%count:(count-i%count);

  12.         for(j=0; j<line-space_num; j++)
  13.             printf("%c",(j < space_num)? 32:ch);
  14.         printf("\n");
  15.     }

  16.     return 0;
  17. }

换一种思路:
  1. int diamond(int count,char ch){
  2.     int row, col;
  3.     int n;

  4.     if((n = count - 1) < 0) {
  5.         printf("Count is error\n");
  6.         return -1;
  7.     }

  8.     for (row = -n; row <= n; row++) {
  9.         for (col = -n; col <= n; col++)
  10.             printf("%c", (fabs(row) + fabs(col) <= n)? ch:32); //<=改成==可以打印空心菱形
  11.         
  12.         printf("\n");
  13.     }

  14.     return 0;
  15. }



阅读(2712) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~