C ++新秀:计算两点之间的距离

时间:2020-04-15 20:14:17

标签: c++

我正在尝试编写一些简单的C ++代码以输出d维点之间的距离。我定义了一个点结构,该结构具有计算到任何其他点的距离的功能。

从两点进行测试,这是行不通的。我认为这可能是sqrt函数不起作用,但是即使函数“ test”输出了double也不起作用。

我正在使用VS Code,输出为...什么都没有。

我确定我缺少一些简单的东西...

#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;
}

3 个答案:

答案 0 :(得分:4)

问题的耦合,有些至关重要,有些是常规的。

  1. 最好将方法传递为constconst方法,以便可以从const对象中使用这些方法。
  2. 要更改d,您应该写point::d = 2而不是int d = 2
  3. d是尺寸,不能为负,因此std::size_tunsigned int
  4. 如果在构造函数上进行分配,则应在析构函数上进行分配。如果有析构函数,则需要一个拷贝构造函数和一个拷贝分配运算符。如果您不知道这些是什么,请不要在构造函数中分配:-)
  5. 请注意,点构造器正在使用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;
}

答案 1 :(得分:1)

您的代码没有执行任何操作,因为在将任何值分配给a b a/b 9 100 0.09 之前,将调用point的构造函数。因此,偶然地,d的值似乎为0(静态变量默认情况下为零初始化)。

这里是修复此类代码的一种可能性:

d

Live Code

答案 2 :(得分:0)

问题是在构造函数运行后设置成员变量d,因此双精度数组始终为0的数组。您应该在构造函数参数中提供d。