Computing the scalar product of two vectors in C++

后端 未结 5 972
一生所求
一生所求 2020-12-31 03:34

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

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 04:31

    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 
    #include 
    #include 
    
    using namespace std;
    
    /**
    This function returns the scalar product of two vectors "a" and "b"
    */
    double scalar_product(vector a, vector 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 veca(2);
        vector 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):

    g++ Scalar.cpp -o scalar
    

    To run it simply type

    ./scalar
    

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

提交回复
热议问题