编程打印钻石怎么弄

时间:2025-01-23 14:44:04 游戏攻略

C++

```cpp

include

using namespace std;

int main() {

int n;

char c;

cin >> n >> c;

for (int j = 0; j < n; j++) {

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

cout << " ";

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

if ((c == 'y') || (i == 0) || (i == 2 * j))

cout << "*";

else

cout << " ";

cout << endl;

}

return 0;

}

```

Java

```java

import java.util.Scanner;

public class PrintDiamond {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the number of rows: ");

int rows = sc.nextInt();

if (rows % 2 == 0) rows++;

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

if (i <= rows / 2) {

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

System.out.print(" ");

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

System.out.print("*");

} else {

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

System.out.print(" ");

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

System.out.print("*");

}

System.out.println();

}

}

}

```

Python

```python

def print_diamond(n, solid):

if solid:

for i in range(n):

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

else:

for i in range(n):

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

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

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

Example usage:

print_diamond(5, True) Prints a solid diamond

print_diamond(5, False) Prints an hollow diamond

```

这些代码示例分别使用C++、Java和Python编程语言实现了打印实心和空心钻石的功能。你可以根据需要选择合适的编程语言和代码示例。