曼哈顿(或城市街区)距离

Manhattan (or city-block) distance

Question can be found here

如果我们查看欧氏距离和曼哈顿距离,它们分别只是 p=2 和 p=1 的特定实例。

对于 p<1,这个距离测量实际上不是一个度量,但有时它可能仍然很有趣。对于这个问题,编写一个程序来计算给定 p 值的点对之间的 p 范数距离。

while(1){

        double x1 = 0,y1 = 0,x2 = 0,y2 = 0, p = 0;
        scanf("%lf", &x1);
        if (x1 == 0.0000000000){
            break;
        }
        scanf("%lf", &y1);
        scanf("%lf", &x2);
        scanf("%lf", &y2);
        scanf("%lf", &p);

        double x_abs = 0, y_abs = 0;

        x_abs = (x1 - x2);
        y_abs = (y1 - y2);

        fabs(x_abs);
        fabs(y_abs);

        double x_calc = 0, y_calc = 0;

        x_calc = pow(x_abs,p);
        y_calc = pow(y_abs,p);

        double result = 0;
        result = x_calc + y_calc;

        double distance = 0;
        distance = pow(result,(1/p));

        if (distance < 0){
            printf("%.10lf\n",(distance*-1));
        }
        else
            printf("%.10lf\n",(distance));
    }

问题是第一个测试用例成功但第二个不成功。看不出问题?你呢?

Input look like this:

1.0 1.0 2.0 2.0 2.0
1.0 1.0 2.0 2.0 1.0
1.0 1.0 20.0 20.0 10.0
0

0 indicates end of input

语句 fabs(x_abs);fabs(y_abs); 什么都不做。 fabs 不会也不能更改传递给它的表达式的值。此错误导致负值作为第一个参数传递给 pow,从而导致域错误,并且当 p 不是整数时可能出现 NaN returns。

要修复它,请更改:

x_abs = (x1 - x2);
y_abs = (y1 - y2);

fabs(x_abs);
fabs(y_abs);

至:

x_abs = fabs(x1 - x2);
y_abs = fabs(y1 - y2);

在你的编译器中打开大多数(-Wmost 在 Clang 中)或“所有”警告(-Wall 在 GCC 或 Clang 中)。当使用 -Wall 时,GCC 和 Clang 都会报告此错误。