Monday, May 24, 2010

Why will this basic vector calculation not work in C++?

#include %26lt;iostream%26gt;


#include %26lt;math.h%26gt;


#include %26lt;conio.h%26gt;


#include %26lt;iomanip%26gt;





using namespace std;





double x[50] = {0.0};


int j, M=5, N=1;


double P[350][350] = {0.0};





int main()


{


for (j = -M; j %26lt; M; j++)


P[N][j] = j+1;





for (j = -M+1; j %26lt; M; j++)


{


x[j] = (1*j)*P[N][j] + (j*(P[N][j+1] + P[N][j-1]));


cout %26lt;%26lt; endl %26lt;%26lt; " x= " %26lt;%26lt; x[j] %26lt;%26lt; endl;


}





getch();


return 0;


}

Why will this basic vector calculation not work in C++?
if M=5, the line for(j=-M;j%26lt;M;j++) will produce a value of -5 for j during the first time through your loop.





Since you use N and j as indicies into the P array, P[N][j] = P[1][-5] this is a problem: you have a negative index into your array.

covent garden

No comments:

Post a Comment