用c++计算两个向量的标量积。

时间:2022-05-10 23:12:31

I am trying to write a program with a function double_product(vector<double> a, vector<double> b) that computes the scalar product of two vectors. The scalar product is

我尝试用一个函数double_product(vector a, vector b)来编写一个程序,计算两个向量的标量积。标量的产品是

$a_{0}b_{0}+a_{1}b_{1}+...+a_{n-1}b_{n-1}$.

Here is what I have. It is a mess, but I am trying!

这就是我所拥有的。这是一团糟,但我正在努力!

#include <iostream>
#include <vector>

using namespace std;

class Scalar_product
{
    public:
    Scalar_product(vector<double> a, vector<double> b);
};
double scalar_product(vector<double> a, vector<double> b)
{
    double product = 0;
    for (int i = 0; i <= a.size()-1; i++)
        for (int i = 0; i <= b.size()-1; i++)
            product = product + (a[i])*(b[i]);
    return product;
}

int main() {
    cout << product << endl;
    return 0;
}

5 个解决方案

#1


35  

Unless you need to do this on your own (e.g., writing it is homework), you should really use the standard algorithm that's already written to do exactly what you want:

除非你需要自己做(比如写作业),你应该使用已经写好的标准算法来做你想做的事情:

#include <iostream>
#include <numeric>

int main() {
    double a[] = {1, 2, 3};
    double b[] = {4, 5, 6};

    std::cout << "The scalar product is: "
              << std::inner_product(std::begin(a), std::end(a), std::begin(b), 0.0);
    return 0;
}

Note that while the begin(a), end(a) is new in C++11, std::inner_product has been available since C++98.

注意,当开始(a)时,end(a)在c++ 11中是新的,std::inner_product从c++ 98开始可用。

#2


10  

You can delete the class you have defined. You don't need it.

您可以删除已定义的类。你不需要它。

In your scalar_product function:

在你scalar_product功能:

double scalar_product(vector<double> a, vector<double> b)
{
    double product = 0;
    for (int i = 0; i <= a.size()-1; i++)
        for (int i = 0; i <= b.size()-1; i++)
            product = product + (a[i])*(b[i]);
    return product;
}

It's almost there. You don't need 2 loops. Just one.

这几乎是在那里。你不需要两个循环。只有一个。

double scalar_product(vector<double> a, vector<double> b)
{
    if( a.size() != b.size() ) // error check
    {
        puts( "Error a's size not equal to b's size" ) ;
        return -1 ;  // not defined
    }

    // compute
    double product = 0;
    for (int i = 0; i <= a.size()-1; i++)
       product += (a[i])*(b[i]); // += means add to product
    return product;
}

Now to call this function, you need to create 2 vector objects in your main(), fill them with values, (the same number of values of course!) and then call scalar_product( first_vector_that_you_create, second_vector_object );

现在,要调用这个函数,您需要在main()中创建两个向量对象,将它们填充为值(当然是相同数量的值!),然后调用scalar_product(first_vector_that_you_create, second_vector_object);

#3


3  

While you have been presented many solutions that work, let me spin up another variation to introduce a couple of concepts that should help you writing better code:

虽然您已经给出了许多解决方案,但是让我再来介绍一些可以帮助您编写更好代码的概念:

  • class are only needed to pack data together
  • 类只需要将数据打包在一起。
  • a function should check its preconditions as soon as possible, those should be documented
  • 一个函数应该尽快检查它的先决条件,这些应该被记录下来。
  • a function should have postconditions, those should be documented
  • 一个函数应该具有后置条件,这些应该被记录。
  • code reuse is the cornerstone of maintenable programs
  • 代码重用是维护程序的基础。

With that in mind:

记住这一点:

// Takes two vectors of the same size and computes their scalar product
// Returns a positive value
double scalar_product(std::vector<double> const& a, std::vector<double> const& b)
{
    if (a.size() != b.size()) { throw std::runtime_error("different sizes"); }

    return std::inner_product(a.begin(), a.end(), b.begin(), 0.0);
} // scalar_product

You could decide to use the inner_product algorithm directly but let's face it:

你可以决定直接使用inner_product算法,但是让我们面对它:

  • it requires four arguments, not two
  • 它需要四个参数,而不是两个。
  • it does not check for its arguments being of the same size
  • 它不检查其参数是否相同。

so it's better to wrap it.

所以最好把它包起来。

Note: I used const& to indicate to the compiler not to copy the vectors.

注意:我使用const&to指示编译器不要复制这些向量。

#4


1  

Here is the code that you should have. I see you have used class in your code, which you do not really need here. Let me know if the question required you to use class.

这是您应该有的代码。我看到您在代码中使用了类,在这里您并不真正需要。如果这个问题需要你去上课,请告诉我。

As you are new and this code might scare you. So, I will try to explain this as I go. Look for comments in the code to understand what is being done and ask if you do not understand.

因为你是新手,这段代码可能会吓到你。所以,我会试着解释一下。在代码中查找注释,了解正在做什么,并询问您是否不理解。

//Scalar.cpp
#include <stdlib.h>
#include <iostream>
#include <vector>

using namespace std;

/**
This function returns the scalar product of two vectors "a" and "b"
*/
double scalar_product(vector<double> a, vector<double> b)
{
    //In C++, you should declare every variable before you use it. So, you declare product and initialize it to 0.
    double product = 0;
    //Here you check whether the two vectors are of equal size. If they are not then the vectors cannot be multiplied for scalar product.
    if(a.size()!=b.size()){
        cout << "Vectors are not of the same size and hence the scalar product cannot be calculated" << endl;
        return -1;  //Note: This -1 is not the answer, but just a number indicating that the product is not possible. Some pair of vectors might actually have a -1, but in that case you will not see the error above.
    }

    //you loop through the vectors. As bobo also pointed you do not need two loops.
    for (int i = 0; i < a.size(); i++)
    {
        product = product + a[i]*b[i];
    }

    //finally you return the product
    return product;
}


 //This is your main function that will be executed before anything else.
int main() {
    //you declare two vectors "veca" and "vecb" of length 2 each
    vector<double> veca(2);
    vector<double> vecb(2);

    //put some random values into the vectors
    veca[0] = 1.5;
    veca[1] = .7;
    vecb[0] = 1.0;
    vecb[1] = .7;

    //This is important! You called the function you just defined above with the two parameters as "veca" and "vecb". I hope this cout is simple!
    cout << scalar_product(veca,vecb) << endl;
}

If you are using an IDE then just compile and run. If you are using command-line on a Unix-based system with g++ compiler, this is what you will do (where Scalar.cpp is the file containing code):

如果您正在使用IDE,那么只需编译并运行。如果您在基于unix的系统上使用g++编译器使用命令行,那么这就是您要做的事情(在这里是标量)。cpp是包含代码的文件):

g++ Scalar.cpp -o scalar

To run it simply type

要运行它,只需键入。

./scalar

You should get 1.99 as the output of the above program.

您应该得到1.99作为上述程序的输出。

#5


0  

You seem to want to make a class specifically for vectors. The class I made in my example is tailored to 3 dimensional vectors, but you can change it to another if desired. The class holds i,j,k but also can conduct a scalar products based on other MathVectors. The other vector is passed in via a C++ reference. It is hard to deduce what the question was, but I think this might answer it.

你似乎想要专门为向量做一个类。我在我的示例中创建的类是针对三维向量进行的,但是如果需要,您可以将其更改为另一个向量。类持有i、j、k,但也可以基于其他数学向量进行标量乘积。另一个向量通过一个c++引用传入。很难推断出这个问题是什么,但我想这可能会回答这个问题。

#include <iostream>

using namespace std;

class MathVector
{
private:
    double i,j,k;
public:
    MathVector(double i,double j,double k)
    {
        this->i=i;
        this->j=j;
        this->k=k;
    }
    double getI(){return i;}
    double getJ(){return j;}
    double getK(){return k;}
    double scalar(MathVector &other)
    {
        return (i*other.getI())+(j*other.getJ())+(k*other.getK());
    }
};

int main(int argc, char **argv)
{
    MathVector a(1,2,5), b(2,4,1);

    cout << a.scalar(b) << endl;

    return 0;
}

#1


35  

Unless you need to do this on your own (e.g., writing it is homework), you should really use the standard algorithm that's already written to do exactly what you want:

除非你需要自己做(比如写作业),你应该使用已经写好的标准算法来做你想做的事情:

#include <iostream>
#include <numeric>

int main() {
    double a[] = {1, 2, 3};
    double b[] = {4, 5, 6};

    std::cout << "The scalar product is: "
              << std::inner_product(std::begin(a), std::end(a), std::begin(b), 0.0);
    return 0;
}

Note that while the begin(a), end(a) is new in C++11, std::inner_product has been available since C++98.

注意,当开始(a)时,end(a)在c++ 11中是新的,std::inner_product从c++ 98开始可用。

#2


10  

You can delete the class you have defined. You don't need it.

您可以删除已定义的类。你不需要它。

In your scalar_product function:

在你scalar_product功能:

double scalar_product(vector<double> a, vector<double> b)
{
    double product = 0;
    for (int i = 0; i <= a.size()-1; i++)
        for (int i = 0; i <= b.size()-1; i++)
            product = product + (a[i])*(b[i]);
    return product;
}

It's almost there. You don't need 2 loops. Just one.

这几乎是在那里。你不需要两个循环。只有一个。

double scalar_product(vector<double> a, vector<double> b)
{
    if( a.size() != b.size() ) // error check
    {
        puts( "Error a's size not equal to b's size" ) ;
        return -1 ;  // not defined
    }

    // compute
    double product = 0;
    for (int i = 0; i <= a.size()-1; i++)
       product += (a[i])*(b[i]); // += means add to product
    return product;
}

Now to call this function, you need to create 2 vector objects in your main(), fill them with values, (the same number of values of course!) and then call scalar_product( first_vector_that_you_create, second_vector_object );

现在,要调用这个函数,您需要在main()中创建两个向量对象,将它们填充为值(当然是相同数量的值!),然后调用scalar_product(first_vector_that_you_create, second_vector_object);

#3


3  

While you have been presented many solutions that work, let me spin up another variation to introduce a couple of concepts that should help you writing better code:

虽然您已经给出了许多解决方案,但是让我再来介绍一些可以帮助您编写更好代码的概念:

  • class are only needed to pack data together
  • 类只需要将数据打包在一起。
  • a function should check its preconditions as soon as possible, those should be documented
  • 一个函数应该尽快检查它的先决条件,这些应该被记录下来。
  • a function should have postconditions, those should be documented
  • 一个函数应该具有后置条件,这些应该被记录。
  • code reuse is the cornerstone of maintenable programs
  • 代码重用是维护程序的基础。

With that in mind:

记住这一点:

// Takes two vectors of the same size and computes their scalar product
// Returns a positive value
double scalar_product(std::vector<double> const& a, std::vector<double> const& b)
{
    if (a.size() != b.size()) { throw std::runtime_error("different sizes"); }

    return std::inner_product(a.begin(), a.end(), b.begin(), 0.0);
} // scalar_product

You could decide to use the inner_product algorithm directly but let's face it:

你可以决定直接使用inner_product算法,但是让我们面对它:

  • it requires four arguments, not two
  • 它需要四个参数,而不是两个。
  • it does not check for its arguments being of the same size
  • 它不检查其参数是否相同。

so it's better to wrap it.

所以最好把它包起来。

Note: I used const& to indicate to the compiler not to copy the vectors.

注意:我使用const&to指示编译器不要复制这些向量。

#4


1  

Here is the code that you should have. I see you have used class in your code, which you do not really need here. Let me know if the question required you to use class.

这是您应该有的代码。我看到您在代码中使用了类,在这里您并不真正需要。如果这个问题需要你去上课,请告诉我。

As you are new and this code might scare you. So, I will try to explain this as I go. Look for comments in the code to understand what is being done and ask if you do not understand.

因为你是新手,这段代码可能会吓到你。所以,我会试着解释一下。在代码中查找注释,了解正在做什么,并询问您是否不理解。

//Scalar.cpp
#include <stdlib.h>
#include <iostream>
#include <vector>

using namespace std;

/**
This function returns the scalar product of two vectors "a" and "b"
*/
double scalar_product(vector<double> a, vector<double> b)
{
    //In C++, you should declare every variable before you use it. So, you declare product and initialize it to 0.
    double product = 0;
    //Here you check whether the two vectors are of equal size. If they are not then the vectors cannot be multiplied for scalar product.
    if(a.size()!=b.size()){
        cout << "Vectors are not of the same size and hence the scalar product cannot be calculated" << endl;
        return -1;  //Note: This -1 is not the answer, but just a number indicating that the product is not possible. Some pair of vectors might actually have a -1, but in that case you will not see the error above.
    }

    //you loop through the vectors. As bobo also pointed you do not need two loops.
    for (int i = 0; i < a.size(); i++)
    {
        product = product + a[i]*b[i];
    }

    //finally you return the product
    return product;
}


 //This is your main function that will be executed before anything else.
int main() {
    //you declare two vectors "veca" and "vecb" of length 2 each
    vector<double> veca(2);
    vector<double> vecb(2);

    //put some random values into the vectors
    veca[0] = 1.5;
    veca[1] = .7;
    vecb[0] = 1.0;
    vecb[1] = .7;

    //This is important! You called the function you just defined above with the two parameters as "veca" and "vecb". I hope this cout is simple!
    cout << scalar_product(veca,vecb) << endl;
}

If you are using an IDE then just compile and run. If you are using command-line on a Unix-based system with g++ compiler, this is what you will do (where Scalar.cpp is the file containing code):

如果您正在使用IDE,那么只需编译并运行。如果您在基于unix的系统上使用g++编译器使用命令行,那么这就是您要做的事情(在这里是标量)。cpp是包含代码的文件):

g++ Scalar.cpp -o scalar

To run it simply type

要运行它,只需键入。

./scalar

You should get 1.99 as the output of the above program.

您应该得到1.99作为上述程序的输出。

#5


0  

You seem to want to make a class specifically for vectors. The class I made in my example is tailored to 3 dimensional vectors, but you can change it to another if desired. The class holds i,j,k but also can conduct a scalar products based on other MathVectors. The other vector is passed in via a C++ reference. It is hard to deduce what the question was, but I think this might answer it.

你似乎想要专门为向量做一个类。我在我的示例中创建的类是针对三维向量进行的,但是如果需要,您可以将其更改为另一个向量。类持有i、j、k,但也可以基于其他数学向量进行标量乘积。另一个向量通过一个c++引用传入。很难推断出这个问题是什么,但我想这可能会回答这个问题。

#include <iostream>

using namespace std;

class MathVector
{
private:
    double i,j,k;
public:
    MathVector(double i,double j,double k)
    {
        this->i=i;
        this->j=j;
        this->k=k;
    }
    double getI(){return i;}
    double getJ(){return j;}
    double getK(){return k;}
    double scalar(MathVector &other)
    {
        return (i*other.getI())+(j*other.getJ())+(k*other.getK());
    }
};

int main(int argc, char **argv)
{
    MathVector a(1,2,5), b(2,4,1);

    cout << a.scalar(b) << endl;

    return 0;
}