所以我試着編寫一個函數來返回兩個向量的標量乘積(即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