查找两点之间的距离

c++ finding distance between 2 points

本文关键字:之间 距离 两点 查找      更新时间:2023-10-16

在我的测试程序中,我有两个点,我想用distancefrom找到它们之间的距离。但我得到的答案是0。

  1. 为什么它给出0?
  2. 我该如何修复它?

    Point<2> v1;//这应该是{0.0,0.0}2> v3 {list{2.0,3.0}};float f = v1.distanceFrom(v3);cout & lt; & lt;f & lt; & lt;endl;

我有一个point.h文件。

#ifndef POINT_H
#define POINT_H
#include <iostream>
#include <list>
#include <sstream>
#include <string>
using std::stringstream;


#include <cmath>

using namespace std;
template<unsigned short n>
class Point {
public:
    list <float> coords = {0.0};
    Point <n>() = default;

    Point <n>(list<float> coords){
        if (coords.size()!=n) {
            throw string ("Vale koordinaatide arv");
        }
        this-> coords=coords;
        }

        string toString(){
            string sone;
            ostringstream ss;
            sone.append("(");
            auto it3= coords.begin();
            while ((it3) != coords.end()){  
                ss <<  (*it3);
                sone.append(ss.str());
                ss.str("");
                sone.append(",");
                ++it3;
                }
                sone.pop_back();
            sone.append(")");
            return sone;
        }

        float distanceFrom (Point <n> v){
            float s=0;
            list<float> coords;
            auto it1= coords.begin();
            auto it2= v.coords.begin();
            while ((it1) != coords.end()){  
                s+=(*it1 -*it2)*(*it1-*it2);
                it1++;
                it2++;
            }
        return sqrt(s);
        }
    friend std::ostream& operator <<(std::ostream& out, const Point<n>& v)
    {
        out << "("<<"Test"<<")";
        return out;
    }
};

#endif

首先,您的coords列表不知道您希望其大小为n。默认初始化后的大小为1:

list <float> coords = {0.0};

正确的构造方法是:

list <float> coords = list <float> (n, 0.0);

第二,在函数distanceFrom:

中分配一个新的coords
list<float> coords;

这会遮蔽你实际想要使用的点的coords。去掉那一行,你就没事了。

#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
class pointDistance{
    int x, y;
    public:
    pointDistance (int a, int b){
        x =a;
        y =b;
    }
    void pointShow(){
        cout<<"The Point is ("<<x<<","<<y<<")"<<endl;
    }
    friend void Distance(pointDistance , pointDistance);
};
//formula of distance between two points:
//d =((x1^2 - x2^2) + (y1^2 - y2^2))^1/2
void Distance(pointDistance o1, pointDistance o2)
{
    // pointDistance o3;
    int d1,d2;
    d1 = (o1.x -o2.x)*(o1.x -o2.x);
    d2 = (o1.y - o2.y)*(o1.y - o2.y);
    cout<<"So the distance between two point is "<< sqrt(d1+d2)<<endl;
}
int main(){
    pointDistance one(4,5);
    one.pointShow();
    pointDistance two(0,6);
    two.pointShow();
    Distance(one, two);
    
 return 0;
}