Java 中的基数方向算法
2022-09-02 23:47:08
这个周末,我花了几分钟时间整理一个算法,该算法将采用标题(以度为单位)并返回基本方向的字符串(我正在使用的Android指南针应用程序中使用它)。我最终得到的是:
private String headingToString(Float heading)
{
String strHeading = "?";
Hashtable<String, Float> cardinal = new Hashtable<String, Float>();
cardinal.put("North_1", new Float(0));
cardinal.put("Northeast", new Float(45));
cardinal.put("East", new Float(90));
cardinal.put("Southeast", new Float(135));
cardinal.put("South", new Float(180));
cardinal.put("Southwest", new Float(225));
cardinal.put("West", new Float(270));
cardinal.put("Northwest", new Float(315));
cardinal.put("North_2", new Float(360));
for (String key: cardinal.keySet())
{
Float value = cardinal.get(key);
if (Math.abs(heading - value) < 30)
{
strHeading = key;
if (key.contains("North_"))
{
strHeading = "North";
}
break;
}
}
return strHeading;
}
我的问题是,这是最好的方法吗?它之前一定已经做过很多次了,尽管我还没有在网上搜索过例子。有没有人尝试过这个并找到一个更整洁的解决方案?
编辑The Reverand的Thilo,shinjin和Chrstoffer的回应:
解决方案
public static String headingToString2(double x)
{
String directions[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"};
return directions[ (int)Math.round(( ((double)x % 360) / 45)) ];
}