编程菱形图案输出怎么做

时间:2025-01-27 20:06:12 网络游戏

方法一:基于三角形的分割

```c

include

int main() {

int n, c, k, space = 1;

printf("Enter number of rows: ");

scanf("%d", &n);

space = n - 1;

// 上半部分

for (k = 1; k <= n; k++) {

for (c = 1; c <= space; c++) printf(" ");

space--;

for (c = 1; c <= 2 * k - 1; c++) printf("*");

printf("\n");

}

// 下半部分

space = 1;

for (k = 1; k <= n - 1; k++) {

for (c = 1; c <= space; c++) printf(" ");

space++;

for (c = 1; c <= 2 * (n - k) - 1; c++) printf("*");

printf("\n");

}

return 0;

}

```

方法二:使用二维数组

```c

include

int main() {

int diamond[] = {

{' ', ' ', '*', ' ', ' '},

{' ', '*', ' ', ' ', ' '},

{'*', ' ', ' ', ' ', ' '},

{' ', '*', ' ', ' ', ' '},

{' ', ' ', '*', ' ', ' '}

};

int i, j;

for (i = 0; i < 5; i++) {

for (j = 0; j < 5; j++) {

printf("%c", diamond[i][j]);

}

printf("\n");

}

return 0;

}

```

方法三:通过控制空格和星号输出

```c

include

int main() {

int n;

printf("Enter number of rows: ");

scanf("%d", &n);

// 上半部分

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= n - i; j++) printf(" ");

for (int k = 1; k <= 2 * i - 1; k++) printf("*");

printf("\n");

}

// 下半部分

for (int i = n - 1; i >= 1; i--) {

for (int j = 1; j <= n - i; j++) printf(" ");

for (int k = 1; k <= 2 * i - 1; k++) printf("*");

printf("\n");

}

return 0;

}

```

方法四:使用Python实现

```python

n = int(input("请输入菱形的边长: "))

for i in range(n):

for j in range(n - i - 1):

print(" ", end="")

for j in range(i + 1):

print(chr(65 + j), end="")

for j in range(i, 0, -1):

print(chr(64 + j), end="")

print()

for i in range(n - 2, -1, -1):

for j in range(n - i - 1):

print(" ", end="")

for j in range(i + 1):

print(chr(65 + j), end="")

for j in range(i, 0, -1):

print(chr(64 + j), end="")

print()

```

这些方法都可以实现菱形的输出,你可以根据自己的需求和编程环境选择合适的方法。