请用Java实现心形函数图像
时间: 2023-05-21 18:02:05 浏览: 128
以下是Java实现心形函数图像的代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class HeartFunction extends JPanel {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 600;
private static final int HEIGHT = 600;
private static final int SCALE = 10;
public HeartFunction() {
setPreferredSize(new java.awt.Dimension(WIDTH, HEIGHT));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
for (double t = -Math.PI; t <= Math.PI; t += 0.01) {
double x = 16 * Math.pow(Math.sin(t), 3);
double y = 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t);
int xScaled = (int) (x * SCALE + WIDTH / 2);
int yScaled = (int) (y * SCALE + HEIGHT / 2);
g.drawLine(xScaled, yScaled, xScaled, yScaled);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Heart Function");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new HeartFunction());
frame.pack();
frame.setVisible(true);
}
}
```
你可以运行这个程序来看到心形函数的图像。
阅读全文