这个周末,我花了几分钟时间匆忙编写了一个算法,它可以接收一个标题(以度为单位),并返回一个代表基本方向的字符串(我在使用安卓指南针应用时使用它)。最终我得到了这个代码:
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)) ];
}
String[] directions = { "N", "NE", "E" ... }
- ThiloString directions[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}
2)索引 8 应该回绕到 0:return directions[(int)Math.round(((double)x % 360) / 45) % 8]
- Andrey