怎么用编程做一个正方形

时间:2025-03-05 10:22:34 明星趣事

要用编程画一个正方形,你可以选择多种编程语言和方法。下面我将提供几种不同编程语言中画正方形的示例代码。

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()

```

Java 使用 AWT 库

```java

import javax.swing.*;

import java.awt.*;

public class SquareDrawer {

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

JFrame frame = new JFrame("Perfect Square Drawer");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 400);

frame.add(new SquarePanel());

frame.setVisible(true);

});

}

static class SquarePanel extends JPanel {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

int width = getWidth();

int height = getHeight();

int squareSize = Math.min(width, height);

int x = (width - squareSize) / 2;

int y = (height - squareSize) / 2;

g.drawRect(x, y, squareSize, squareSize);

}

}

}

```

JavaScript 使用 Canvas API

```javascript

function drawSquare(sideLength, color) {

const canvas = document.createElement('canvas');

const ctx = canvas.getContext('2d');

ctx.beginPath();

ctx.fillStyle = color;

for (let i = 0; i < 4; i++) {

if (i === 0) {

ctx.moveTo(0, 0);

}

ctx.lineTo(sideLength * (i + 1), 0);

ctx.lineTo(sideLength * (i + 1), sideLength);

ctx.lineTo(0, sideLength);

ctx.closePath();

}

ctx.fill();

}

// 调用函数,传入边长为50,颜色为红色

drawSquare(50, 'red');

```

Scratch 编程软件

在 Scratch 中,你可以使用以下代码来绘制一个正方形:

```scratch

when green flag clicked

repeat 4

forward 100

turn 90 degrees

end

```

这些示例代码展示了如何使用不同的编程语言和工具来绘制一个正方形。你可以根据自己的需求和熟悉程度选择合适的方法。