所以我尝试编写一个可以返回两个 vector 的标量积的函数(即 a0b0 + a1b1 + ...),但是每当我运行该程序时,它只会读取第一组输入(即 vector a),然后第二个 vector ( vector b)被自动“跳过”,程序返回一个非常奇怪的数字,如 2.122e-314。那么这段代码有什么问题呢? (为简单起见,我假设 vector a 和 b 具有相同的大小。)谢谢!
#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;
}
最佳答案
您需要在读取第一个 vector 后调用 cin.clear()
来重置错误标志。正如 Peter 所提到的,您还需要忽略 cin
中的非数字字符。您可以使用 cin.ignore(10000,'\n');
之类的方法来执行此操作,它将忽略所有字符,直到换行为止。
关于c++ - 该程序不会读取 C++ 中的第二个 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23023101/