Python
使用turtle模块绘制正方形:
```python
import turtle
def draw_square(length):
turtle.speed(1) 设置绘制速度
for _ in range(4):
turtle.forward(length) 向前移动指定长度
turtle.right(90) 向右旋转90度
side_length = int(input("请输入正方形的边长: "))
draw_square(side_length)
turtle.done()
```
Java
使用Swing库绘制正方形:
```java
import javax.swing.*;
import java.awt.*;
public class SquareDrawer {
public static void main(String[] args) {
JFrame frame = new JFrame("Draw Square");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.add(new SquarePanel());
frame.setVisible(true);
}
}
class SquarePanel extends JPanel {
private int sideLength = 100;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLACK);
int x = (getWidth() - sideLength) / 2;
int y = (getHeight() - sideLength) / 2;
g2d.fillRect(x, y, sideLength, sideLength);
}
}
```
C++
使用SFML库绘制正方形:
```cpp
include include int main() { sf::RenderWindow window(sf::VideoMode(800, 600), "Draw Square"); sf::RectangleShape square(sf::Vector2f(100.f, 100.f)); square.setFillColor(sf::Color::Red); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(); window.draw(square); window.display(); } return 0; } ``` C 使用WinForms绘制正方形: ```csharp using System; using System.Drawing; using System.Windows.Forms; public class SquareForm : Form { private int sideLength = 100; public SquareForm() { this.ClientSize = new Size(800, 600); this.BackColor = Color.White; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; g.FillRectangle(Brushes.Red, 0, 0, sideLength, sideLength); } [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new SquareForm()); } } ``` 这些示例代码展示了如何使用不同的编程语言和图形库来绘制正方形。你可以根据自己的需求和熟悉程度选择合适的编程语言和库来实现正方形的绘制。