【发布时间】:2017-09-18 14:56:45
【问题描述】:
我正在尝试编写计算两个给定向量的点积的 C++ 程序。在向量 a 和 b 中,只有非零元素将存储到结构数组中。每次我得到不相关的结果。正确的结果是 50。我认为我无法将向量正确读取到结构数组中。请指教。提前谢谢你
#include <iostream>
#include <vector>
using namespace std;
const int n=10; /* vector size limit */
struct element {
int x; /* original index of non-zero array element */
int val ; /* integer non-zero value at index x */
};
element row[n];
element col[n];
int i;
vector<int> a={0,0,7,0,5,0,0,8,0,4,-1};
vector<int> b={0,0,0,5,6,0,0,0,0,5,-1};
void generate_row_and_col()
{
for (i=0; i<=n; i++)
{
if(a[i]=!0)
{
row[i].x=i;
row[i].val=a[i];
}
}
for (i=0; i<=n; i++)
{
if(b[i]!=0)
{
col[i].x=i;
col[i].val=b[i];
}
}
}
int dotproduct()
{
/* calculate the dot product of row and col output the result*/
int i=0;
int j=0;
int product=0;
while(row[i].x!=-1 && col[j].x!=-1)
{
if(row[i].x == col[j].x)
{
product=product+row[i].val*col[j].val;
i++;
j++;
}
else if(row[i].x<col[j].x)
{
i++;
}
else
{
j++;
}
}
return product;
}
int main()
{
generate_row_and_col() ;
int r;
r=dotproduct();
cout<<"result="<<r<<endl;
return 0;
}
【问题讨论】:
-
你的结果应该是 51 而不是 50
-
for (i=0; i<=n; i++)在 C++ 数组索引中从 0...n-1 开始,其中 n = 数组长度。 -
5*6+4*5+-1*-1 = 51
-
我可以看到一个错误 if(a[i]=!0) 那是什么
标签: c++ arrays loops vector structure