用程序怎么写空心菱形

时间:2025-01-28 06:20:07 单机游戏

C语言

```c

include

void show(int n, char c);

int main() {

int n;

scanf("%d", &n);

if (n % 2 != 0)

lingxing(n);

else

puts("Error!");

return 0;

}

void lingxing(int n) {

int i;

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

show(n - i, ' ');

putchar('*');

show(2 * i - n, ' ');

if (i != 1)

putchar('*');

putchar('\n');

}

}

void show(int n, char c) {

int i;

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

putchar(c);

}

putchar('\n');

}

```

C++

```cpp

include

public:

static void printHollowRhombus(int size);

int main() {

int size;

std::cout << "请输入菱形的大小: ";

std::cin >> size;

printHollowRhombus(size);

return 0;

}

void printHollowRhombus(int size) {

if (size % 2 == 0)

size++;

for (int i = 0; i < size; i++) {

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

std::cout << " ";

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

if (j == 0 || j == 2 * i)

std::cout << "*";

else

std::cout << " ";

}

std::cout << std::endl;

}

for (int i = size / 2 + 1; i < size; i++) {

for (int j = 0; j < i - size / 2; j++)

std::cout << " ";

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

if (j == 0 || j == 2 * (size - i) - 1)

std::cout << "*";

else

std::cout << " ";

}

std::cout << std::endl;

}

}

```

Python

```python

def print_hollow_diamond(n):

if n % 2 == 0:

n += 1

for i in range(n):

if i == n // 2:

print("*" * n)

else:

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

print_hollow_diamond(7)

```

这些程序分别使用C语言、C++和Python编写,可以根据需要选择合适的编程语言来实现空心菱形。