當我輸入這些座標時,我得到一個錯誤的輸出。該功能輸出錯誤的值
static double ReadCoordinateFromConsole(double lat1, double lon1, double
lat2, double lon2)
{
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2 - lat1);
var dLon = deg2rad(lon2 - lon1);
var a =
Math.Sin(dLat/2) * Math.Sin(dLat/2) +
Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) *
Math.Sin(dLon/2) * Math.Sin(dLon/2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
var d = R * c; // Distance in km
return d;
}
static double deg2rad(double deg)
{
return deg * (Math.PI/180);
}
然後在我的函數中輸入一些座標。 41.507483 -99.436554 38.504048 -98.315949。這些座標應該約等於347,但是我得到的輸出是7022,88,這是錯誤的,我不知道爲什麼。
static double ReadDoubleFromConsole(string msg)
while (true)
{
Console.Write(msg);
string test = Console.ReadLine();
string[] words = test.Split(' ');
bool inputContainsNumber = Regex.IsMatch(words[0], @"^-*[0-9,\.]+$");
bool inputContainsNumber2 = Regex.IsMatch(words[1], @"^-*[0-9,\.]+$");
bool inputContainsNumber3 = Regex.IsMatch(words[2], @"^-*[0-9,\.]+$");
bool inputContainsNumber4 = Regex.IsMatch(words[3], @"^-*[0-9,\.]+$");
if(inputContainsNumber && inputContainsNumber2 && inputContainsNumber3
&& inputContainsNumber4)
{
double test1 = double.Parse(words[0]);
double test2 = double.Parse(words[1]);
double test3 = double.Parse(words[2]);
double test4 = double.Parse(words[3]);
double test5 = ReadCoordinateFromConsole(test1, test2, test3,
test4);
return test5;
}
Console.WriteLine("hmm, doesn't look correct - try again");
}
}
您是否嘗試過[使用調試器來逐步通(https://www.google.com/search?q =在+ visual + studio中使用+ debugger +)並在每個步驟查看你的計算結果? – Reddog
你試圖實施的數學公式是什麼?此外,爲什麼當它沒有這樣的事情時,你的方法叫做'ReadCoordinateFromConsole'? –
我已經使用了確切的代碼,使用相同的輸入,得到了347.328 ....並且公式看起來正確,所以我不明白你做錯了什麼。 –