为什么这个daxpy在c ++中不起作用?

时间:2013-05-17 19:17:10

标签: c++ vector

我有这个代码,假设做两个向量的daxpy操作并输出结果,但是当我运行它时它给了我3个4(我认为它假设给我3个6)。

我觉得好像缺少关于daxpy的关键重要性,但我不知道它是什么。

以下是代码:

#include <iostream>
using namespace std;



extern "C"
{

    double daxpy_(double *A, double *B, int *n, double *a);
//The daxpy fortran function shown above multiplies a first matrix 'A' by a constant 'a'
//and adds the result to a second matrix 'B.' Both matrices are of size 'n.'
}

void daxpy(double *A, double *B, int n, double a);
//The function above is declared in order to utilize c-notation to perform the fortran
//daxpy function which takes a first matrix 'A' and multiplies the matrix by a costant 'a'
//and then adds the result to a second matrix 'B.'

int main(int argc, char *argv[])
{
    double A[3], B[3];
    int n=3;
    double a=1.0;
    for (int i=0;i<3;i++)
    {
        A[i]=2;
        B[i]=4;
    }
    daxpy(A, B, n, a);
    for (int i=0;i<3;i++)
    {
        cout << B[i] << endl;
    }
}

void daxpy(double *A, double *B, int n, double a)
{
  for (int i=0;i<n;i++)
  {
    B[i]=daxpy_(A, B, &n, &a);
  }
}

2 个答案:

答案 0 :(得分:2)

你不打算这样做:

for (int i=0;i<3;i++)
{
    A[i]=2;
    B[i]=4;
}

那你和你正在访问数组范围之外的索引。对于数组大小为3,最大索引为A [2]。

答案 1 :(得分:1)

这是关于daxpy的信息!最后!我对代码进行了评论,以便更容易理解。我把daxpy称为完全错误。这会工作!!!

答案是6 6 6!

#include <iostream>
using namespace std;


extern "C" //This is important to get the function from the -lblas library you will use when compiling
{
    double daxpy_(int *n, double *a, double *A, int *incA, double *B, int *incB);
//The daxpy fortran function shown above multiplies a first matrix 'A' by a constant 'a'
//and adds the result to a second matrix 'B.' Both matrices are of size 'n.'
}

void daxpy(int n, double a, double *A, int incA, double *B, int incB);
//The function above is declared in order to utilize c-notation to perform the fortran
//daxpy function which takes a first matrix 'A' and multiplies the matrix by a costant 'a'
//and then adds the result to a second matrix 'B.'

int main(int argc, char *argv[])
{
    double A[3], B[3]; //Just initializing and filling up some matrices here
    int n=3, incA=1, incB=1;
    double a=1.0;
    for (int i=0;i<3;i++)
    {
        A[i]=2;
        B[i]=4;
    }
    daxpy(n, a, A, incA, B, incB); //This is the important part! Note the call notation
    for (int i=0;i<3;i++)
    {
        cout << B[i] << endl;
    }
}

void daxpy(int n, double a, double *A, int incA, double *B, int incB)
{
    daxpy_(&n, &a, A, &incA, B, &incB); //Once again, note the call notation. Important!
}

如何编译:{{1​​}}