怎么用编程打金字塔游戏

时间:2025-01-28 05:50:23 网络游戏

1. C语言

```c

include

int main() {

int i, j, n;

printf("请输入金字塔层数: ");

scanf("%d", &n);

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

for (j = 1; j <= n - i; j++) {

printf(" ");

}

for (j = 1; j <= 2 * i - 1; j++) {

printf("*");

}

printf("\n");

}

return 0;

}

```

2. Java

```java

public class Pyramid {

public static void main(String[] args) {

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

for (int x = 1; x <= 5 - i; x++) {

System.out.print(" ");

}

for (int y = 1; y <= 2 * i - 1; y++) {

System.out.print("*");

}

System.out.print("\n");

}

}

}

```

3. C语言(倒金字塔)

```c

include

int main() {

int i, j, n;

printf("请输入倒金字塔的层数: ");

scanf("%d", &n);

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

for (j = 1; j <= i - 1; j++) {

printf(" ");

}

for (j = 1; j <= 2 * n - 2 * i; j++) {

printf("*");

}

printf("\n");

}

return 0;

}

```

4. C语言(字符金字塔)

```c

include

int main() {

int rows;

char ch = 'A';

printf("请输入金字塔的行数: ");

scanf("%d", &rows);

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

for (int j = 1; j <= rows - i; j++) {

printf(" ");

}

for (int j = 1; j <= 2 * i - 1; j++) {

printf("%c", ch);

if (ch == 'Z') {

ch = 'A';

} else {

ch++;

}

}

printf("\n");

}

return 0;

}

```

5. Python

```python

def print_pyramid(n):

for i in range(1, n + 1):

print(" " * (n - i) + "*" * (2 * i - 1))

n = int(input("请输入金字塔的层数: "))

print_pyramid(n)

```

这些代码示例展示了如何使用不同编程语言(如C语言、Java、Python)来打印金字塔形状。你可以选择适合你的编程语言,并根据需要进行调整和扩展。