在c++中创建一个动态链接库,用于不断计算数学函数

Creating a dll in C++ which is used to constantly calculate maths function

本文关键字:用于 计算 函数 动态链接库 一个 创建 c++      更新时间:2023-10-16

我遇到了一个问题。我试图创建一个dll,可以计算2点之间的距离,当我发送2个不同的值集。然而,当我发送我的第二组值时,我意识到我的第一组值在数组中丢失了(数组用于存储值)

下面是我的代码:
int click = 0;   //click is used to measure the number of times i have clicked, ie to say the number of times im injecting new (a,b) points into the function below.
double MeasureDistance(double a, double b)
{
    /******* Create Array to Store The Points ********/
    /** Initializing the array **/
    double xDistance =0;
    double yDistance =0;
    double TDistance = 0;
    static double **Array;
    int column = 0; //used to toggle the column number
    int width = 100;
    int height = 100;
    Array = new double *[width];
    for (int i=0; i <width; i++)
    {
        Array [i] = new double [height];
    }
    /*** Now a and b are stored inside the Array[0][0] ***/
    for (column =0; column <2; column ++)
    {
        if ((column % 2)==0)
        {
            Array [click][column] = a; //storing at [0,0]
        }
        else 
        {   
            Array [click][column] = b; //storing at [0,1]
        }
    }
                for (int row = 2; row < click; row ++)
    {
        for (column = 0; column <2; column ++)
        {   
            if ((column % 2) == 0)
            {
                xDistance = Array [0][column] - Array [row][column];
            }
            else
            {
                yDistance = Array [0][column] - Array [row][column];
            }
        }
        TDistance = sqrt((xDistance * xDistance) + (yDistance * yDistance));
    }
/*** Clearing up of array ***/
    for (int i = 0; i < width; i++)
    {
        delete[] Array[i];
    }
    delete[] Array;

click++;
    return TDistance ;
}

我意识到,当我注入我的第二组a和b值,我的值在数组[0][0]和[0][1]丢失,但我的第二组值存储在[1][0]和[1][1]。任何想法我可以运行这个脚本而不失去以前的值?提前感谢。修改代码以清除一些查询

使用Array = new double *[width];行,您在每个函数调用中初始化您的数组。如果你需要存储值(我非常怀疑),最好使用静态初始化向量。但是一般来说,让函数的结果依赖于先前的调用是一个非常糟糕的主意。如果您确实需要累积状态,请考虑为此目的创建一个函数对象。

编辑:

使用函数对象,您可以通过更改operator()和通过成员变量保存数据的数据结构来更改算法的行为。

编辑2:您可能需要这样的内容:

struct MeasureDistance {
  double last_x;
  double last_y;
  MeasureDistance() : last_x(0), last_y(0) {}
  double operator()(double new_x, double new_y) {
    double diff_x=last_x-new_x;
    double diff_y=last_y-new_y;
    double result=sqrt(diff_x*diff_x,diff_y*_diff_y);
    last_x=new_x;
    last_y=new_y;
    return result;
};
MeasureDistance md;
cout 
  << md(0.0, 1.0) << 'n' //prints 1
  << md(2.0, 1.0) << 'n' //prints 2
  ;