正當自己無所事事時,朋友給我布置了一項作業,如下圖:
一乍聽,我還挺害怕的,以為很高深的問題,但因為給出了計算公式,實作起來并不難。将上圖中的公式拆解開來,并加上輸入、輸出功能基本上就算完成了。
輸入
使用者需要輸入離散點個數n和相應的坐标(x,y,z)、公式裡面的beta以及目标點的坐标(x,y)
根據計算需要,先設計點的資料結構:
struct Point{
public double x;
public double y;
public double z;
public double d; //該點距目标點的距離
public double w; //權重
}
聲明所需要的離散點數組points、變量n和beta以及目标點point;
/*全局變量*/
static Point[] points; //使用者存放離散點
static Point point = new Point();//目标點
/*局部變量*/
int n=; //離散點個數
int beta=; //beta值,一般設為1或2
/*資料輸入*/
Console.Write("請輸入離散點個數n:");
n = Convert.ToInt32(Console.ReadLine());
w=new double[n];
points=new Point[n];
Console.Write("請輸入beta值(建議值1或2):");
beta = Convert.ToInt32(Console.ReadLine());
//下面輸入每一個離散點的坐标
Console.WriteLine("****************\n下面輸入離散點坐标(格式為:x,y,z:");
for(int i=;i<n;i++){
Console.Write("第{0}個點坐标:",i+);
string[]str1=Console.ReadLine().Split(',');
points[i].x=Convert.ToDouble(str1[]);
points[i].y=Convert.ToDouble(str1[]);
points[i].z=Convert.ToDouble(str1[]);
}
//下面輸入要計算的點的坐标
Console.Write("離散點輸入完成\n最後再輸入目标點的坐标(格式為:x,y:\n目标點:");
string[] str2 = Console.ReadLine().Split(',');
point.x = Convert.ToDouble(str2[]);
point.y = Convert.ToDouble(str2[]);
point.z = ; //初始化為0
計算過程
計算過程細分為三個小部分:
1.計算各離散點至目标點的距離;
2.計算權重;
3.計算最終的高程值
//計算距離,每一個離散點至目标點的平面距離
static void GetDistance()
{
for (int i = ; i < points.Length; i++)
{
points[i].d = Math.Sqrt(Math.Pow((point.x - points[i].x), ) + Math.Pow((point.y - points[i].y), ));
}
}
//擷取分母,計算中會用到
static double GetFenmu(int beta)
{
double fenmu = ;
for (int i = ; i < points.Length; i++)
{
fenmu += Math.Pow((/points[i].d),beta);
}
return fenmu;
}
//計算權重
static void GetWeight(int beta)
{
//權重是距離的倒數的函數
double fenmu = GetFenmu(beta);
for (int i = ; i < points.Length; i++)
{
points[i].w = Math.Pow(( / points[i].d),beta) / fenmu;
}
}
//得到最終高程值
static void GetTargetZ()
{
for (int i = ; i < points.Length; i++)
{
point.z += points[i].z * points[i].w;
}
}
結果輸出
就是展示咯
//純粹為了展示
static void ShowPoints()
{
Console.WriteLine("計算結果:");
Console.WriteLine("點号\tx\ty\tz\td\tw");
for (int i = ; i < points.Length; i++)
{
Console.WriteLine("No.{0}\t{1}\t{2}\t{3}\t{4}\t{5}", i + , points[i].x, points[i].y, points[i].z, points[i].d.ToString("#0.000"), points[i].w.ToString("#0.000"));
}
}
下載下傳