编程代码怎么画正方形的

时间:2025-03-04 14:33:03 明星趣事

使用编程语言绘制正方形的方法取决于你使用的编程语言和可用的库。以下是几种常见编程语言中绘制正方形的示例代码:

Python

使用`turtle`库绘制正方形:

```python

import turtle

def draw_square(side_length):

for _ in range(4):

turtle.forward(side_length)

turtle.right(90)

turtle.done()

draw_square(100)

```

使用循环和打印字符绘制正方形:

```python

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

for i in range(side_length):

for j in range(side_length):

print("*", end=" ")

print()

```

Java

使用`Graphics`类绘制正方形:

```java

import java.awt.*;

import javax.swing.*;

public class DrawSquare extends JPanel {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

g.drawRect(50, 50, 100, 100);

}

public static void main(String[] args) {

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

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(new DrawSquare());

frame.setSize(200, 200);

frame.setVisible(true);

}

}

```

C

使用`System.Drawing`命名空间绘制正方形:

```csharp

using System;

using System.Drawing;

using System.Windows.Forms;

public class DrawSquare : Form {

protected override void OnPaint(PaintEventArgs e) {

base.OnPaint(e);

e.Graphics.DrawRectangle(Pens.Black, 50, 50, 100, 100);

}

[STAThread]

static void Main() {

Application.EnableVisualStyles();

Application.Run(new DrawSquare());

}

}

```

JavaScript (HTML5 Canvas)

使用HTML5 Canvas元素绘制正方形:

```html

Your browser does not support the HTML5 canvas tag.