[英]C++ rookie: calculating distance between two points
我正在尝试编写一些简单的 C++ 代码到 d 维度中点之间的 output 距离。 我定义了一个点结构,它有一个 function 用于计算到任何其他点的距离。
在两点上测试它,它不起作用。 我认为这可能是 sqrt function 不起作用,但即使是 function “测试”输出双精度也不起作用。
我正在使用 VS Code,而 output 是......什么都没有。
我确定我错过了一些简单的东西......
#include <iostream>
#include <cmath>
using namespace std;
struct point
{
static int d;
double *coords;
point(){ //point class
coords=new double[d];
for (int i=0; i<d; i++){
coords[i]=0;
}
}
double dist(point &q){
double squared=0;
for (int i=0; i<d;i++){
squared+=(coords[i]-q.coords[i])*(coords[i]-q.coords[i]);
}
return sqrt(squared);
}
double test(){
return 1.4;
}
};
int point::d;
int main() {
point p;
int d=2;
p.d=d;
p.coords[0]=1;
p.coords[1]=1;
point q;
q.d=d;
q.coords[0]=0;
q.coords[1]=2;
std::cout << "\ndistance:" << p.dist(q)<<"\n\n";
std::cout << "even this doesn't work!:" << p.test()<<"\n\n";
return 0;
}
几个问题,有些是至关重要的,有些是常规的。
const
和const
传递,以便您可以从 const object 中使用这些方法。d
,你应该写point::d = 2
而不是int d = 2
d
是维度,不能为负数,因此为std::size_t
或unsigned int
point::d
,因此您应该在创建 p 的任何实例之前设置point::d
。我附上了您的代码并应用了我的修复程序
struct point
{
static std::size_t d;
double *coords;
point() { //point class
coords = new double[d];
for (int i = 0; i < d; i++) {
coords[i] = 0;
}
}
double dist(const point &q) const {
double squared = 0;
for (int i = 0; i < d; i++) {
squared += (coords[i] - q.coords[i])*(coords[i] - q.coords[i]);
}
return sqrt(squared);
}
double test() const {
return 1.4;
}
point(const point& p) {
coords = new double[d];
for (std::size_t i = 0; i < d; ++i) {
coords[i] = p.coords[i];
}
}
point& operator=(const point& p) {
if (this == &p) {
return *this;
}
// coords are already allocated
for (std::size_t i = 0; i < d; ++i) {
coords[i] = p.coords[i];
}
}
~point() {
delete[] coords;
}
};
std::size_t point::d;
int main() {
point::d = 2;
point p;
p.coords[0] = 1;
p.coords[1] = 1;
point q;
q.coords[0] = 0;
q.coords[1] = 2;
std::cout << "\ndistance:" << p.dist(q) << "\n\n";
std::cout << "even this doesn't work!:" << p.test() << "\n\n";
return 0;
}
您的代码什么也不做,因为在您将任何值分配给d
之前将调用point
的构造函数。 因此,意外地, d
的值似乎为 0(静态变量默认为零初始化)。
这是修复此类代码的一种可能性:
#include <iostream>
#include <cmath>
using namespace std;
struct point
{
constexpr static int d = 2;
double coords[d];
point(){ //point class
for (int i=0; i<d; i++){
coords[i]=0;
}
}
double dist(point &q){
double squared=0;
for (int i=0; i<d;i++){
squared+=(coords[i]-q.coords[i])*(coords[i]-q.coords[i]);
}
return sqrt(squared);
}
};
int main(){
point p;
p.coords[0]=1;
p.coords[1]=1;
point q;
q.coords[0]=0;
q.coords[1]=2;
std::cout << "\ndistance:" << p.dist(q)<<"\n\n";
return 0;
}
问题是您在构造函数运行后设置成员变量 d ,因此您的双精度数组始终是 0 数组。您应该在构造函数参数中提供 d 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.