-
1.2.1编写一个Point2D的用例,从命令行接受一个整数N。在单位正方形中生成N个随机点,然后计算两点的最近距离。
-
解析:
1、用Chart建立一个离散图
2、两点距离公式:Math.Sqrt((x2-x1)2+(y2-y1)2); -
代码
namespace Graph
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1_TextChanged(null, null);
}private void textBox1_TextChanged(object sender, EventArgs e) { int num = 0; try { num = Convert.ToInt32(textBox1.Text.Trim());//必须为正整数 } catch { return; } if (num <= 0) { return; } List<Point2D> listpoint = new List<Point2D>(); while (listpoint.Count < num) { Point2D point2D = new Point2D(); point2D.Xz = Randomnums(); point2D.Yz = Randomnums(); if (!listpoint.Contains(point2D)) { listpoint.Add(point2D); } } SuperChart superChart = new SuperChart(chart1); superChart.ShowChart( System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, listpoint); textBox2.Text=ShortestDis(listpoint).ToString(); }
//用时间作为种子生成随机数这样就不会出现一直重复的问题
public int Randomnums()
{
var Seed = Guid.NewGuid().GetHashCode();
var value = new Random(Seed);
return value.Next(1, 100);
}//两点距离公式:Math.Sqrt((x2-x1)^2+(y2-y1)^2); public double ShortestDis(List<Point2D> listpoint) { int n = listpoint.Count - 1; double shortest = (listpoint[n].Xz - listpoint[0].Xz) * (listpoint[n].Xz - listpoint[0].Xz) + (listpoint[n].Yz - listpoint[0].Yz) * (listpoint[n].Yz - listpoint[0].Yz); for(int i=0;i< listpoint.Count; i++) { for(int j= i+1;j< listpoint.Count; j++) { double temp= (listpoint[i].Xz - listpoint[j].Xz) * (listpoint[i].Xz - listpoint[j].Xz) + (listpoint[i].Yz - listpoint[j].Yz) * (listpoint[i].Yz - listpoint[j].Yz); if(temp< shortest) { shortest = temp; } } } return Math.Sqrt(shortest); }
}
}
//点的位置
namespace Graph
{
public class PointGraph
{
public class Point2D
{
public double Xz { get; set; }
public double Yz { get; set; }
}
}
}
//图形绘制
namespace Graph
{
public class SuperChart
{
private Chart chart = null;
public SuperChart(Chart chart)
{
this.chart = chart;
}
///
/// 绘制图标的通用方法
///
/// 图标类型
/// 数据
public void ShowChart ( SeriesChartType chartType,List dataList)
{
//[1]清除所有的图标序列
this.chart.Series.Clear();
//[2]创建一个图表序列对象(一个图表可以添加多个图表序列,也就是绘图对象)
Series series1 = new Series();
series1.ChartType = chartType;//设置图表的序列类型
this.chart.Series.Add(series1);//添加到图表的序列集合
//[3]设置图表序列的各种属性值
for(int i = 0; i < dataList.Count; i++)
{
//3.1 获取数据对象的两个值
double xz = dataList[i].Xz;
double yz = dataList[i].Yz;
//3.2 使用x和y的值将DataPoint对象添加进去
series1.Points.AddXY(xz, yz);
series1.Points[i].Label = string.Format(“X:{0},Y:{1}”, xz, yz);
}
//[4]设置图表绘图区域的X和Y坐标值(Y:具体表示要显示数据之间的间隔)
this.chart.ChartAreas[0].AxisY.Maximum = 100;
this.chart.ChartAreas[0].AxisY.Minimum = 0;
this.chart.ChartAreas[0].AxisX.Maximum = 100;
this.chart.ChartAreas[0].AxisX.Minimum = 0;
this.chart.ChartAreas[0].AxisX.Interval = 20;
this.chart.ChartAreas[0].AxisY.Interval = 20;
}
}
}