```c#
using System;
namespace A
{
class Program
{
class Tra
{
static public double Earth = 6378137.0;
public void Computing(string lat_a, string lng_a,string lat_b,string lng_b,out double s,out double d)
//其中lat_a, lng_a是A的纬度和经度; lat_b, lng_b是B的纬度和经度
{
double aw, aj, bw, bj;
aw = Hdu(lat_a);
aj = Hdu(lng_a);
bw = Hdu(lat_b);
bj = Hdu(lng_b);
// 计算两点距离disdance
s = Earth * 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin((bw -aw) / 2), 2) + Math.Cos(bw) * Math.Cos(aw) * Math.Pow(Math.Sin((bj - aj) / 2), 2)));
// 计算方位角pab
double x = Math.Sin(bj - aj) * Math.Cos(bw);
double y = Math.Cos(aw) * Math.Sin(bw) - Math.Sin(aw) * Math.Cos(bw) * Math.Cos(bj- aj);
double a = Math.Atan2(x, y);
d = Mod(a,Math.PI);
}
public double Hdu(string s)
{ //将度分秒转换为弧度
string[] ss = s.Split(new char[3] { '°', '′', '″' }, StringSplitOptions.RemoveEmptyEntries);//分割字符串,删除空字符
double[] d = new double[ss.Length];//新建一个双精度的数值数组
for (int i = 0; i < d.Length; i++)
d[i] = Convert.ToDouble(ss[i]);//将度分秒存入双精度的数值数组中
double sign = d[0] >= 0.0 ? 1.0 : -1.0;//判断正负
double rad = 0;
if (d.Length == 1)//根据数组长度进行判断计算
rad = (Math.Abs(d[0])) * Math.PI / 180;//将度取绝对值,并转换成弧度
else if (d.Length == 2)
rad = ((Math.Abs(d[0])) + d[1] / 60) * Math.PI / 180;
else
rad = ((Math.Abs(d[0])) + d[1] / 60 + d[2] / 60 / 60) * Math.PI / 180;
rad = sign * rad;//弧度前边添加正负号
return rad;//返回弧度值
}
public double Mod(double n, double d)
{
double c = n - d * Math.Floor(n / d);
return c;
}
}
static void Main(string[] args)
{ //输入输出所要演示的代码
Console.WriteLine("请输入待计算点的纬度、经度坐标");
string lat_a = Console.ReadLine();
string lng_a = Console.ReadLine();
string lat_b = Console.ReadLine();
string lng_b = Console.ReadLine();
double s, d;
Tra MyArithmetic = new Tra();
MyArithmetic.Computing(lat_a,lng_a,lat_b,lng_b,out s, out d);
Console.WriteLine("两点之间的距离及方位角为\n");
Console.WriteLine("{0},{1}", s, d);
Console.ReadKey();
}
}
}
调试代码后按一下回车无结果,连按数次以后出现如下报错
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at A.Program.Tra.Hdu(String s) in D:\测绘编程技术\A\A\Program.cs:line 36
at A.Program.Tra.Computing(String lat_a, String lng_a, String lat_b, String lng_b, Double& s, Double& d) in D:\测绘编程技术\A\A\Program.cs:line 17
at A.Program.Main(String[] args) in D:\测绘编程技术\A\A\Program.cs:line 62