Ecco il codice che si dovrebbe avere. Vedo che hai usato la classe nel tuo codice, di cui non hai davvero bisogno qui. Fammi sapere se la domanda richiedesse di usare la lezione.
Come sei nuovo e questo codice potrebbe spaventarti. Quindi, cercherò di spiegarlo mentre vado. Cerca i commenti nel codice per capire cosa si sta facendo e chiedi se non capisci.
//Scalar.cpp
#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
/**
This function returns the scalar product of two vectors "a" and "b"
*/
double scalar_product(vector<double> a, vector<double> 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 << "Vectors are not of the same size and hence the scalar product cannot be calculated" << 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 < 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<double> veca(2);
vector<double> 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 << scalar_product(veca,vecb) << endl;
}
Se si utilizza un IDE, è sufficiente compilare ed eseguire. Se si utilizza da riga di comando su un sistema Unix-based con il compilatore g ++, questo è ciò che si fa (dove Scalar.cpp è il file di codice che contiene):
g++ Scalar.cpp -o scalar
per eseguirlo è sufficiente digitare
./scalar
Si dovrebbe ottenere 1.99
come output del programma di cui sopra.
C'è davvero una domanda qui? –
Che cos'è "bouble"? – jakebird451
La tua domanda non è molto chiara. Abbiamo capito che sono i tuoi compiti. Ma quale domanda stai cercando di risolvere e aggiungere un piccolo dettaglio su quale problema stai affrontando? – Ankit