Aquí está el código que debe tener. Veo que usaste clase en tu código, que realmente no necesitas aquí. Avíseme si la pregunta requirió que use la clase.
Como es nuevo y este código puede asustarlo. Entonces, intentaré explicar esto a medida que avance. Busque comentarios en el código para comprender lo que se está haciendo y pregúntele si no comprende.
//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;
}
Si está utilizando un IDE, simplemente compile y ejecute. Si está utilizando la línea de comandos en un sistema basado en Unix con el compilador g ++, esto es lo que va a hacer (donde Scalar.cpp es el código que contiene el archivo):
g++ Scalar.cpp -o scalar
para ejecutarlo simplemente escriba
./scalar
Debe obtener 1.99
como resultado del programa anterior.
¿Hay alguna pregunta aquí? –
¿Qué es "bouble"? – jakebird451
Su pregunta no es muy clara. Lo conseguimos que es tu tarea. Pero, ¿qué pregunta está tratando de resolver y agregar un pequeño detalle sobre el problema que está enfrentando? – Ankit