i'm having difficulties finding problem here , program must read number n , read 2 vectors n lenght, multiply each number of first vector relevant number of second 1 , substract each of previous multiplies (example a[0]*b[0] - a[1]*b[1] .... a[n-1]*b[n-1] ) replies appreciated. input values : 3/ 1 2 -3 /4 -5 -6 output : -4 here's code:
#include <iostream> #include <string> #include <sstream> #include <vector> #include <cstdlib> using namespace std; /* splits string using whitespace delimeter */ void split_input(vector<double> &vector_values, const string &input) { char delim = ' '; stringstream mysstream(input); string temp; while(getline(mysstream, temp, delim)) { vector_values.push_back(atof(temp.c_str())); } } double multiply(vector<double> &first_vector, vector<double> &second_vector) { double result = 0; for(int = 0; < first_vector.size(); i++) { if (i == 0) { result = first_vector[i]*second_vector[i]; } else { result -= first_vector[i]*second_vector[i]; } cout << result << endl; } return result; } int main() { vector<double> first_vector; vector<double> second_vector; int num; string input_values; cout << "please enter number: " << endl; cin >> num ; /* ignores endline char previous cin */ cin.ignore(); /* read first string, split , store values in vector */ getline(cin, input_values); split_input(first_vector, input_values); cin.ignore(); /* read second string, split , store values in vector */ getline(cin, input_values); split_input(second_vector, input_values); /* multiply vectors */ cout << multiply(first_vector, second_vector) << endl; return 0; }
remove cin.ignore()
after split_input(first_vector, input_values);
. cin.ignore()
first element of second vector alway 0
. main()
should this:
int main() { vector<double> first_vector; vector<double> second_vector; int num; string input_values; cout << "please enter number: " << endl; cin >> num ; /* ignores endline char previous cin */ cin.ignore(); /* read first string, split , store values in vector */ getline(cin, input_values); split_input(first_vector, input_values); // following line causes first element of second vector become 0 // cin.ignore(); /* read second string, split , store values in vector */ getline(cin, input_values); split_input(second_vector, input_values); /* multiply vectors */ cout << multiply(first_vector, second_vector) << endl; return 0; }
Comments
Post a Comment