Computing the scalar product of two vectors in C++

后端 未结 5 973
一生所求
一生所求 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:18

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

    In your scalar_product function:

    double scalar_product(vector a, vector 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 a, vector 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 );

提交回复
热议问题