Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>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.</p> <pre><code>//Scalar.cpp #include &lt;stdlib.h&gt; #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; /** This function returns the scalar product of two vectors "a" and "b" */ double scalar_product(vector&lt;double&gt; a, vector&lt;double&gt; 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 &lt;&lt; "Vectors are not of the same size and hence the scalar product cannot be calculated" &lt;&lt; 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 &lt; 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&lt;double&gt; veca(2); vector&lt;double&gt; 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 &lt;&lt; scalar_product(veca,vecb) &lt;&lt; endl; } </code></pre> <p>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):</p> <pre><code>g++ Scalar.cpp -o scalar </code></pre> <p>To run it simply type</p> <pre><code>./scalar </code></pre> <p>You should get <code>1.99</code> as the output of the above program.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload