每当我输入这些坐标时,我都会得到错误的输出。
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");
}
}
最佳答案
正如其他答案向您展示的那样,您的算法是正确的 - 您对用户输入的解析是错误的!
这是演示:http://rextester.com/IEEA93176
原因是,在 rextester 在 中运行的文化中,
被用作小数点分隔符 - 我假设它在您的环境中是相同的。当您在需要 的区域中使用
您得到的值是 double.parse("41.1234")
时,411234
而不是 41.1234
.
一个解决办法是强制文化
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
现场演示(工作):http://rextester.com/KALRN89806
关于c# - 函数输出错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46050702/