0

So I am a new to this. 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

$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<bouble> 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;

}
  • Welcome to Programmers! Please check out the [FAQ], as it seems like your question is off-topic here. Perhaps [SO] is a better place to find your answer? Although, it's not quite clear what your problem really is. If you do ask your question elsewhere, please provide more information so it's clearer for the folks wanting to answer. – Jeremy Jun 06 '12 at 03:54
  • any suggestions where I can get help? –  Jun 06 '12 at 03:56
  • Hello! As @JeremyHeiler already mentioned, this is off topic for us and it might fit in a sister site, Stack Overflow or Code Review. But before I can migrate it to either, you need to tell us _exactly_ what is the problem with your code, i.e. what does "It is a mess" means. If it means the code is _not_ working, then I'd migrate the question to Stack Overflow (provided you tell us how it's not working), but if it means that you feel the code is sub par (but working) and want a critique of it, I'd send it to Code Review. – yannis Jun 06 '12 at 04:06
  • 1
    possible duplicate of [Computing the scalar product of two vectors in C++](http://stackoverflow.com/questions/10908012/computing-the-scalar-product-of-two-vectors-in-c) – Ben Voigt Jun 06 '12 at 14:35

2 Answers2

2

You have a pretty correct idea, at the fundamental level. A couple of basic building blocks extra and you'll be well on your way. Your scalar_product function is close, but not quite. You've created two loop iterators with the same name iterating over the same values. It should be fine to simply say

if (a.size() != b.size()) {} // error
for (int i=0; i < a.size(); i++)
   product = product + (a[i])*(b[i]);

Now all you have to do is get some data, call it, and then output the result.

int main() {
    std::vector<double> a;
    std::vector<double> b;
    // fill with the values
    std::cout << scalar_product(a, b) << endl;
}

The whole class thing is completely unnecessary here- the only classes you need come in the Standard lib.

Puppy
  • 144,682
  • 38
  • 256
  • 465
2

since I cannot comment I am forced to reply.

apparently there is exactly the same question, word by word, here:

Computing the scalar product of two vectors in C++

Community
  • 1
  • 1
Federico
  • 1,092
  • 3
  • 16
  • 36