八角芒星用编程怎么做

时间:2025-01-29 01:33:32 网络游戏

使用Python的turtle库

```python

import turtle

def draw_star(size):

turtle.bgcolor("white")

turtle.color("black")

turtle.pensize(3)

for _ in range(8):

turtle.forward(size)

turtle.right(45)

turtle.done()

获取用户输入的八角星大小

n = int(input("请输入八角星的大小: "))

draw_star(n)

```

使用Python的嵌套循环

```python

def print_star(n):

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

for j in range(2 * n - 1):

if i == n - 1 or j == n - 1 or i + j == n - 1 or i - j == n - 1:

print("*", end="")

else:

print(" ", end="")

print()

获取用户输入的八角星大小

n = int(input("请输入八角星的大小: "))

print_star(n)

```

使用Python的tkinter库

```python

from tkinter import *

import math

def draw_star(canvas, center_x, center_y, r):

canvas.create_polygon((center_x - int(r * math.sin(2 * math.pi / 5)), center_y - int(r * math.cos(2 * math.pi / 5))),

(center_x + int(r * math.sin(2 * math.pi / 5)), center_y - int(r * math.cos(2 * math.pi / 5))),

(center_x + int(r * math.sin(4 * math.pi / 5)), center_y - int(r * math.cos(4 * math.pi / 5))),

(center_x - int(r * math.sin(4 * math.pi / 5)), center_y - int(r * math.cos(4 * math.pi / 5))),

(center_x, center_y - r),

(center_x + int(r * math.sin(2 * math.pi / 5)), center_y + int(r * math.cos(2 * math.pi / 5))),

(center_x - int(r * math.sin(2 * math.pi / 5)), center_y + int(r * math.cos(2 * math.pi / 5))),

(center_x - int(r * math.sin(4 * math.pi / 5)), center_y + int(r * math.cos(4 * math.pi / 5))),

(center_x + int(r * math.sin(4 * math.pi / 5)), center_y + int(r * math.cos(4 * math.pi / 5))),

fill="black")

base = Tk()

canvas = Canvas(base, width=300, height=300, background='grey')

canvas.pack()

center_x = 150

center_y = 150

r = 150

draw_star(canvas, center_x, center_y, r)

base.mainloop()

```

这些代码示例分别使用了turtle库、嵌套循环和tkinter库来绘制八角星。你可以根据自己的需求和编程环境选择合适的代码进行尝试。