c++ - 如何用C语言计算两点之间距离(超大数据)?
大家讲道理
大家讲道理 2017-04-17 14:32:50
0
4
910

//计算x y之间距离
double distance(point a,point b){

return sqrt(    (a.x - b.x)*(a.x - b.x)  +   (a.y -b.y)*(a.y -b.y)  );

}

想要直接以这样的公式计算,但是当输入大于六位数会出错。需要输入小于等于1000000的数字。
所以有没有能够数据不溢出的解决方法。
当然计算结果只需要保留后两位即可。

参考代码:

#include <stdio.h>
#include <stdlib.h>
#include "math.h"
typedef struct point {
    double x;
    double y;
}point;
point array[30001];

double distance(point a,point b);
int main(int argc, char *argv[]) 
{
    while(1){


    int n,i,j,count;
    double maxdis,temp;
    scanf("%d",&n);
    for(i = 0;i<n;i++){
        scanf("%f %f",&array[i].x,&array[i].y);
        
    }
    for(i = 0;i<n;i++){
        //printf("%d %d\n",array[i].x,array[i].y);
        //printf("dis:%.2f\n",distance(array[0],array[i]));

    }
    maxdis = 0.0;
    for(i = 0;i<n;i++){
        for(j = i;j<n;j++){
            if(distance((array[i]),(array[j])) > maxdis ){
                //printf("maxdis = :%.2f\n",distance((array[i]),(array[j])));
                maxdis =distance((array[i]),(array[j]));
            }
        }
    }
    printf("%.2f",maxdis);
    
}
    
    
    system("pause");
    return 0;
}

//计算x y之间距离
double distance(point a,point b){
    return sqrt(    (a.x - b.x)*(a.x - b.x)  +   (a.y -b.y)*(a.y -b.y)  );
}

代码已经贴出。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
Ty80

Please post the definition of point...
To be honest, if it is only 1 million W, double is easy and stress-free. Could it be that int is used...?

大家讲道理

I made the following modifications to your code:
Changed the scanf reading type from %f to %lf. The input data cannot be read using %f on my machine.
There is no problem compiling on my computer and the running results are normal.
The comment above has already solved this problem.

左手右手慢动作

Use high precision directly for very large numbers. This has nothing to do with whether the distance is calculated

Peter_Zhu

To tell you something unrelated to the problem... you can try using high precision.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template