问题描述
我正在尝试使用图形以特定间隔绘制函数 y = x ^ 2,但我不能。当我写 start + = 1/10 (以增加点数)时,会消除索引超出数组的错误,在这种情况下,它现在是什么,图形看起来不像它应该的那样。也许有人可以帮助我使用 Graphics 构建此图表。 P.S:是的,我知道我可以使用图表,但任务是通过图形来完成。
using System.Drawing;
using System.Windows.Forms;
namespace FormsForProgrammin
{
public partial class Form15 : Form
{
PointF[] p = new PointF[10];
int count = 0;
public Form15()
{
InitializeComponent();
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form15_Paint);
Calc();
}
private void Calc()
{
float start = float.Parse(textBox1.Text);
while(start<= float.Parse(textBox2.Text))
{
float res = start * start;
p[count] = new PointF(start,res);
count += 1;
start += 1;
}
}
private void Form15_Paint(object sender,PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.drawing2d.SmoothingMode.AntiAlias;
e.Graphics.TranslateTransform(150,150);
e.Graphics.ScaleTransform(1,0.25F);
e.Graphics.DrawLines(Pens.Blue,p);
}
}
}
解决方法
您有一个由 10 个点组成的数组,并且您正在使用 count 变量对它们进行索引。您在该代码中有几个问题:
- 你从不重置计数
- 您将 start 设置为 textBox1 值,并将其递增 1,直到它超过 textBox2 值。但这个差距可能大于你在数组中的点数
要解决 1,您可以在循环完成后重置计数,或者简单地在 Calc 方法本身中定义计数(后者将是更好的选择,因为计数仅与 Calc 方法相关)
要解决 2,您需要计算步数:值之间的差异除以点数, 使用此步骤量来确保循环运行的次数不会超过您拥有的点数