function - Writing a program in C++ and I need help -
so new this. trying write program function
double_product(vector< double > a, vector< double > b) computes scalar product of 2 vectors. scalar product
$a_{0}b_{0}+a_{1}b_{1}+...a_{n-1}b_{n-1}$.
here have. mess, 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; (int i=0; <=a.size()-1; i++) (int i=0; <=b.size()-1; i++) product = product + (a[i])*(b[i]); return product; } int main() { cout << product << endl; return 0; }
you have pretty correct idea, @ fundamental level. couple of basic building blocks , you'll on way. scalar_product function close, not quite. you've created 2 loop iterators same name iterating on same values. should fine say
if (a.size() != b.size()) {} // error (int i=0; < a.size(); i++) product = product + (a[i])*(b[i]); now have data, call it, , output result.
int main() { std::vector<double> a; std::vector<double> b; // fill values std::cout << scalar_product(a, b) << endl; } the whole class thing unnecessary here- classes need come in standard lib.
Comments
Post a Comment