查找两点之间的距离
c++ finding distance between 2 points
在我的测试程序中,我有两个点,我想用distancefrom找到它们之间的距离。但我得到的答案是0。
- 为什么它给出0?
-
我该如何修复它?
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;
}
相关文章:
- 用C++程序计算圆锥体的体积、球体的体积、八边形的面积和两点之间的距离
- 计算所有对之间的曼哈顿距离
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 两个有符号数字之间的距离
- 计算车辆之间的距离并设置速度,使距离保持不变,例如 5 米
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 查找彼此之间具有不同最小距离的随机数
- 相同字符之间的最小距离
- 如何排列二进制字符串以最小化它们之间的距离
- 堆和堆栈之间的距离
- 树节点之间的最大距离中的运行时错误
- 最接近的字符串:在字符串阵列中找到2个字符串之间的最小距离
- 尝试查找数组中点之间的最小距离时的随机垃圾输出
- c++ 从大型数组中读取 3D 坐标并计算它们之间的距离
- 在 OpenCV 中计算 SURF 功能之间的距离
- 计算机如何分配两个变量,我们如何计算两个变量之间的距离?
- 是否有C 功能来计算两个索引之间的距离
- 使用 DirectXMath 获得 2 点之间距离的最佳方法是什么
- <random> 点之间距离最小的uniform_real_distribution
- 确定景观中所有点与具有特定属性的点之间距离的最快方法