您的位置:首页 > 编程语言 > C语言/C++

C语言基础练习——打印菱形

2020-08-26 18:25 1266 查看

C语言基础练习——打印菱形

JERRY_Z. ~ 2020 / 8 / 26 转载请注明出处!<3

代码:

/*
* @Author: JERRY_Z.
* @Date: 2020-08-26 17:17:38
* @LastEditTime: 2020-08-26 18:09:48
* @FilePath: \undefinede:\MyCode\Blog\C算法题\打印菱形\打印菱形.c
*/

#include <stdio.h>

int main(void){

int n;              //用于接收用户输入的菱形行数

printf("Please enter the row number of the diamond (odd number) n:");
scanf("%d", &n);

int h1 = 0;         //计数器 h1:从0起,记录当前行号为整体的第几行
int h2 = 0;         //计数器 h2:从0起,记录当前行号为整体后半段的第几行

while (h1 < n) {                        //行循环

++h1;                                //进入新一行,h1+1

int k = 0;                           //计数器 k:从0起,记录当前行的起始空格数
int x = 0;                           //计数器 x:从0起,记录当前行的 '*' 数

if (h1 <= (n/2)+1) {                  //行号属于菱形的上半段时执行

while (k <= (n/2)+1-h1) {         //循环打印起始空格
printf(" ");
++k;
}

while (x != h1) {                 //循环打印 '*' 号
printf("* ");
++x;
}

}//if

else {                               //行号属于菱形的下半段时执行

++h2;                            //进入菱形后半段新一行,h2+1

while (k <= h2) {                 //循环打印起始空格
printf(" ");
++k;
}

while (x != n-h1+1) {             //循环打印 '*' 号
printf("* ");
++x;
}

}//else

printf("\n");   //行末尾换行

}//while

return 0;
}

运行结果:

附:

交流方式:

❤️ ❤️ ❤️

QQ: 1846334075

WeChat: zhoujirui54

CSDN:https://blog.csdn.net/D_si_God

Cnblogs:https://www.cnblogs.com/JERRY-Z-J-R/

GitHub:https://github.com/JERRY-Z-J-R

Gitee:https://gitee.com/JERRY-Z-J-R

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: