所以我试着编写一个函数来返回两个向量的标量乘积(即a0b0 + a1b1 + ...),但是每当我运行程序时,它都会只读取第一组输入(即矢量a),然后第二个矢量(矢量b)自动“跳过”,程序返回一个非常奇怪的数字,如2.122e-314。那么这个代码有什么问题? (为了简单起见,我只是假设向量a和b具有相同的大小。)Thx!程序不会读取C++中的第二个向量
#include <iostream>
#include <vector>
using namespace std;
/**
Calculates the scalar product of two vectors.
@param a, b two vectors
@return the sum of product of two vectors: a0b0 + a1b1 + ...
*/
double scalar_product (vector<double>& a, vector<double>& b)
{
double product;
for (int i = 0; i < a.size(); i++)
product += a[i] * b[i];
return product;
}
/**
Reads in a new vector.
*/
vector<double> read (vector<double>& a)
{
bool more = true;
while (more)
{
double s;
cin >> s;
if (cin.fail())
more = false;
else
a.push_back(s);
}
return a;
}
int main()
{
vector<double> a;
cout << "Please enter the numbers of the first series, enter any non-number character to quit: ";
read (a);
vector<double> b;
cout << "Please enter the numbers of the second series, enter any non-number character to quit: ";
read (b);
cout << "The scalar product of the two series is " << scalar_product(a, b) << "\n";
return 0;
}
并且在尝试读取更多数字之前,您可能需要删除即从cin中读取挂起的非数字输入。 –
所以我在“more = false”之后添加了“cin.clear()”,现在它要求我在第二个系列中输入;然而,当我输入一个数字“例如2”时,它告诉我“错误:2不是有效的命令”。这是为什么? – JupiterM
JupiterM:请参阅我对“cin.ignore”的回答的修订。 – GWW