不使用平方根的两点之间的距离

Rap*_*phm 6 c distance points square-root

是否可以在不使用 math.h 库的情况下计算两点之间的距离?我知道,使用 math.h 库,它必须是以下几行(欧几里德距离公式)中的一些内容:

int Distance(int x1, int y1, int x2, int y2)

    {
    int dx = x2 - x1;
    int dy = y2 - y1;
    return sqrt(dx*dx + dy*dy);
    }
Run Code Online (Sandbox Code Playgroud)

但是,有没有办法在不使用平方根(需要 math.h 库)的情况下做完全相同的事情?

编辑:每当我尝试以下代码时,它都会给我浮点异常(核心转储):

float sqrt(int x) {
        int i;
        float s;
        s=((x/2)+x/(x/2)) / 2; /*first guess*/
        for(i=1;i<=4;i++) { /*average of guesses*/
            s=(s+x/s)/2;
        }
        return s;
    }

float Distance(float x1, float y1, float x2, float y2) {
    float dx = x2 - x1;
    float dy = y2 - y1;
    return sqrt(dx*dx + dy*dy);
}

int main() {
  printf("%f", Distance(1, 2, 2, 1));
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

BLU*_*IXY 5

int int_sqrt(int x){
    int s, t;

    s = 1;  t = x;
    while (s < t) {
        s <<= 1;
        t >>= 1;
    }//decide the value of the first tentative

    do {
        t = s;
        s = (x / s + s) >> 1;//x1=(N / x0 + x0)/2 : recurrence formula
    } while (s < t);

    return t;
}
Run Code Online (Sandbox Code Playgroud)


Thi*_*ame 0

网格上的距离​​计算通常使用涉及平方根计算的公式。实际上,在不调用标准 C 库中的 sqrt() 函数的情况下计算平方根的唯一方法是重新实现它,但效果很差。

你为什么要这么做?(或者您是在问,“如何在不计算平方根的情况下做到这一点”?这不再是一个编程问题。)