Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 确定两点是否接近_C#_.net_Vb.net_Math - Fatal编程技术网

C# 确定两点是否接近

C# 确定两点是否接近,c#,.net,vb.net,math,C#,.net,Vb.net,Math,我有以下资料: bool AreNear(Point Old, Point Current) { int x1 = Convert.ToInt32(Old.X); int x2 = Convert.ToInt32(Current.X); int y1 = Convert.ToInt32(Old.Y); int y2 = Convert.ToInt32(Current.Y); if (x1 == x2) { if (y1 == y2) {

我有以下资料:

bool AreNear(Point Old, Point Current)
{
    int x1 = Convert.ToInt32(Old.X);
    int x2 = Convert.ToInt32(Current.X);
    int y1 = Convert.ToInt32(Old.Y);
    int y2 = Convert.ToInt32(Current.Y);
    if (x1 == x2) {
        if (y1 == y2) {
            return true;
        }
    }
    return false;
}

如果当前点在旧点的25像素半径内,我想在函数中返回true。有人能告诉我怎么做吗?

用毕达哥拉斯定理计算距离的平方,然后与半径的平方比较:

bool ComparePoints(Point Old, Point Current)
{
    int x1 = Convert.ToInt32(Old.X);
    int x2 = Convert.ToInt32(Current.X);
    int y1 = Convert.ToInt32(Old.Y);
    int y2 = Convert.ToInt32(Current.Y);
    int dx = x1 - x2;
    int dy = y1 - y2;
    return (dx*dx + dy*dy) < 25*25;
}
bool比较点(旧点、当前点)
{
int x1=转换为32(旧的.X);
int x2=转换为32(当前X);
int y1=转换为INT32(旧的.Y);
int y2=转换为INT32(当前Y);
int dx=x1-x2;
int dy=y1-y2;
返回(dx*dx+dy*dy)<25*25;
}
您可以使用来计算两点之间的距离。在C#中:

为什么这样做有效?查看下图,记住
a^2+b^2=c^2
适用于直角三角形:

您可以使用来获取距离:

public static bool InDistance(Point Old, Point Current, int distance)
{
    int diffX = Math.Abs(Old.X - Current.X);
    int diffY = Math.Abs(Old.Y - Current.Y);
    return diffX <= distance && diffY <= distance;
}

尝试使用距离公式并比较距离这将检查新点是否在旧点的
25
像素平方内(即,它使用最大度量)。度量的不错替代选择:)PS:我会为函数使用更具描述性的名称,例如,
AreNear
。否则,如果(比较点(旧的,当前的))语句的含义不能在不查看子例程本身的情况下推断出来。什么类型是
X
Y
?字符串?+1,用于在不需要时避免那些缓慢的平方根。
public static bool InDistance(Point Old, Point Current, int distance)
{
    int diffX = Math.Abs(Old.X - Current.X);
    int diffY = Math.Abs(Old.Y - Current.Y);
    return diffX <= distance && diffY <= distance;
}
bool arePointsInDistance = InDistance(new Point(100, 120), new Point(120, 99), 25);