我在这里找不到问题很困难,程序必须读取数字N然后读取2个向量与N长度,将第一个向量的每个数字与第二个向量的相关数字相乘并减去前面的每一个乘法(例A [0] * B [0] - A [1] * B [1] .... A [N-1] * B [N-1])任何回复都将不胜感激。 输入值:3 / 1 2 -3 / 4 -5 -6 输出:-4 这是代码:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>
using namespace std;
/* Splits string using whitespace as 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 i = 0; i < 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 a number: " << endl;
cin >> num ;
/* Ignores the endline char from the previous cin */
cin.ignore();
/* Read first string, split it and store the values in a vector */
getline(cin, input_values);
split_input(first_vector, input_values);
cin.ignore();
/* Read second string, split it and store the values in a vector */
getline(cin, input_values);
split_input(second_vector, input_values);
/* Multiply vectors */
cout << multiply(first_vector, second_vector) << endl;
return 0;
}
答案 0 :(得分:0)
在cin.ignore()
之后移除split_input(first_vector, input_values);
。使用cin.ignore()
,第二个向量的第一个元素始终为0
。您的main()
应如下所示:
int main()
{
vector<double> first_vector;
vector<double> second_vector;
int num;
string input_values;
cout << "Please enter a number: " << endl;
cin >> num ;
/* Ignores the endline char from the previous cin */
cin.ignore();
/* Read first string, split it and store the values in a vector */
getline(cin, input_values);
split_input(first_vector, input_values);
// following line causes the first element of the second vector to become 0
// cin.ignore();
/* Read second string, split it and store the values in a vector */
getline(cin, input_values);
split_input(second_vector, input_values);
/* Multiply vectors */
cout << multiply(first_vector, second_vector) << endl;
return 0;
}