我必须检测该点是否属于该区域(已附上图片)。 我写的条件好像太长了。我很确定有一种方法可以用更简单的方式编写它,但我只是不知道该怎么做。 我尝试过的所有代码中唯一成功的代码如下所示。
float x, y; int a = 2, b = 1, r = 3;
printf("x = ", x);
scanf ("%f", &x);
printf("y = ", y);
scanf ("%f", &y);
if ( ((pow((x-a), 2) + pow((y-b), 2) <= pow(r,2)) && ((pow((x-a), 2) + pow((y-b),2) >= 1)) && (x <= 2) && (x >= -3) && (y >= -1) && (y <= 4)) || fabs(x) <= 1 && fabs(y) <=1 || (y == x+2 && y >= -1 && x >= -3))
{
printf ("Belongs to the area");
}
else
{
printf ("Doesn't belong to the area");
}
输出是正确的,所以我希望它是一样的。
最佳答案
也许是这个:
(可选)如果在白色矩形外,返回false。
如果在红色三角中,则返回true。
如果在黄色圈内,则返回false。
如果在绿色矩形内,则返回true。
如果在粉圈外,则返回false。
如果在蓝色矩形内,则返回true。
如果不是以上,则返回false。
第一步是可选的,保存一些检查。如果您的大部分测试点远离您的区域,这将提高性能。
代码示例(未经测试,不是真正的 C 语言专家):
bool point_in_rectangle(double x, double y, double min_x, double max_x, double min_y, double max_y) {
if (x < min_x) return false;
if (x > max_x) return false;
if (y < min_y) return false;
if (y > max_y) return false;
return true;
}
// "easy" means it's properly aligned and has height equal to width
bool point_in_easy_triangle(double x, double y, double min_x, double max_x, double base_y) {
if (x < min_x) return false;
if (x > max_x) return false;
if (y < base_y) return false;
if (x - min_x < y - base_y) return false;
return true;
}
bool point_in_circle(double x, double y, double center_x, double center_y, double radius) {
double distance_x = x - center_x;
double distance_y = y - center_y;
double distance_squared = distance_x * distance_x + distance_y * distance_y;
return distance_squared < (radius * radius);
}
bool point_in_my_area(double x, double y) {
if (!point_in_rectangle(x, y, -3, 2, -1, 4)) return false;
// etc...
}
关于c - 有没有办法用更短的方式编写检测点是否属于区域的条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58464619/