Вот код, который у вас должен быть. Я вижу, вы использовали класс в своем коде, который вам действительно не нужен. Дайте мне знать, если вопрос требует, чтобы вы использовали класс.
Поскольку вы новичок, и этот код может вас напугать. Поэтому я попытаюсь объяснить это, когда я пойду. Ищите комментарии в коде, чтобы понять, что делается, и спросите, не понимаете ли вы.
//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;
}
Если вы используете IDE, тогда просто компилируйте и запускайте. При использовании командной строки на системе Unix основе с компилятором г ++, это то, что вы будете делать (где Scalar.cpp это файл, содержащий код):
g++ Scalar.cpp -o scalar
Чтобы запустить его просто наберите
./scalar
В качестве выхода вышеуказанной программы вы должны получить 1.99
.
На самом деле вопрос здесь? –
Что такое "bouble"? – jakebird451
Вопрос не очень ясен. Мы понимаем, что это ваша домашняя работа. Но какой вопрос вы пытаетесь решить и добавить немного подробностей о том, с какими проблемами вы столкнулись? – Ankit