一.描述
打印一个n行的实心菱形。
二.核心代码
1.多个循环
1.1.代码
void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < abs(n / 2 - i); j++)
printf(" ");
for (int k = 0; k < 2 * (n / 2 + 1 - abs(n / 2 - i)) - 1; k++)
printf("*");
printf("\n");
}
}
1.2.结果
![](https://img2022.cnblogs.com/blog/2177087/202210/2177087-20221013113213816-697414457.png)
2一个循环
2.1.代码
void print() {
int flag = 1;
while (linecount < n) {
if (flag <= abs(n/2 - linecount)) {
printf(" ");
flag++;
}
else if (flag > abs(n / 2 - linecount) + 2 * (n / 2 + 1 - abs(n / 2 - linecount)) - 1) {
printf("\n");
linecount++;
flag = 1;
}
else {
printf("*");
flag++;
}
}
2.2.结果
![](https://img2022.cnblogs.com/blog/2177087/202210/2177087-20221013113320423-1221527333.png)
3.完整代码
#include<stdio.h>
#include<math.h>
int n;
int linecount = 0;
void init() {
printf("请输入n:");
scanf("%d", &n);
}
void print() {
int flag = 1;
while (linecount < n) {
if (flag <= abs(n/2 - linecount)) {
printf(" ");
flag++;
}
else if (flag > abs(n / 2 - linecount) + 2 * (n / 2 + 1 - abs(n / 2 - linecount)) - 1) {
printf("\n");
linecount++;
flag = 1;
}
else {
printf("*");
flag++;
}
}
}
/*void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < abs(n / 2 - i); j++)
printf(" ");
for (int k = 0; k < 2 * (n / 2 + 1 - abs(n / 2 - i)) - 1; k++)
printf("*");
printf("\n");
}
}*/
int main() {
init();
print();
return 0;
}