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;
}
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.
since I cannot comment I am forced to reply.
apparently there is exactly the same question, word by word , here:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.