给定指南针上的任意两个点(起始范围和结束范围)以形成一个范围。例如,从270度(开始范围)到45度(结束范围),并给出另一个点,例如7,我如何计算出该点是否在开始范围和结束范围之间?
我正在尝试写一些代码来计算风(在上面的点3)是从海洋还是从陆地吹来的,陆地是根据开始范围和结束范围来确定的。
非常感谢安迪
更新:11/10/2010 18:46BST来自@sth的解决方案以下内容似乎如预期的那样有效。
#!/usr/bin/perl -w
sub isoffshore {
my ( $beachstart,$beachend,$wind) = @_;
if( $beachend < $beachstart) {
$beachend += 360;
}
if ($wind < $beachstart){
$wind += 360;
}
if ($wind <= $beachend){
print ("Wind is Onshore\n");
return 0;
}else{
print ("Wind is Offshore\n");
return 1;
}
}
isoffshore ("0","190","3"); #Should be onshore
isoffshore ("350","10","11"); #Should be offshore
isoffshore ("270","90","180");#Should be offshore
isoffshore ("90","240","0"); #Should be offshore
isoffshore ("270","90","180");#Should be offshore
isoffshore ("0","180","90"); #Should be onshore
isoffshore ("190","0","160"); #Should be offshore
isoffshore ("110","240","9"); #Should be offshore
isoffshore ("0","180","9"); #Should be onshore
isoffshore ("0","180","179"); #Should be onshore结果
@localhost ~]$ ./offshore2.pl
Wind is Onshore
Wind is Offshore
Wind is Offshore
Wind is Offshore
Wind is Offshore
Wind is Onshore
Wind is Offshore
Wind is Offshore
Wind is Onshore
Wind is Onshore发布于 2010-10-12 16:06:05
下面是一个使用模运算符(%)处理环绕情况的单行函数。假定输入值在0..359 (度)范围内:
int inRange(int start, int end, int point)
{
return (point + 360 - start) % 360 <= (end + 360 - start) % 360;
}
//
// Test harness
//
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
assert(inRange(90, 270, 0) == 0);
assert(inRange(90, 270, 45) == 0);
assert(inRange(90, 270, 180) == 1);
assert(inRange(90, 270, 315) == 0);
assert(inRange(270, 90, 0) == 1);
assert(inRange(270, 90, 45) == 1);
assert(inRange(270, 90, 180) == 0);
assert(inRange(270, 90, 315) == 1);
if (argc >= 4)
{
int start = atoi(argv[1]);
int end = atoi(argv[2]);
int point = atoi(argv[3]);
int result = inRange(start, end, point);
printf("start = %d, end = %d, point = %d -> result = %d\n", start, end, point, result);
}
return 0;
}请注意,由于%处理负值的不幸方式,在C/C++中需要在测试的每一端使用+ 360术语。
发布于 2010-10-11 23:21:39
如果你所有的点都像0 <= point < 360,这应该是可行的
def between(lower, upper, point):
if upper < lower:
upper += 360
if point < lower:
point += 360
return (point <= upper)https://stackoverflow.com/questions/3907495
复制相似问题