怎么编程画正方形图案

时间:2025-01-27 16:28:14 网络游戏

Python 使用 turtle 库

```python

import turtle

def draw_square(side_length):

for _ in range(4):

turtle.forward(side_length)

turtle.right(90)

调用函数并传入边长为5的正方形

draw_square(5)

turtle.done()

```

Python 使用标准输入

```python

side_length = int(input("请输入正方形的边长: "))

for i in range(side_length):

for j in range(side_length):

print("*", end=" ")

print()

```

Java

```java

import java.awt.*;

import javax.swing.*;

public class SquareDrawing {

public static void main(String[] args) {

JFrame frame = new JFrame("Draw a Square");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 400);

frame.setBackground(Color.WHITE);

JPanel panel = new JPanel() {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(Color.BLACK);

g2d.fillRect(50, 50, 100, 100);

}

};

frame.add(panel);

frame.setVisible(true);

}

}

```

JavaScript

```html

Draw a Square