samedi 18 juin 2016

Array won't hold variables outside of a loop c++


I am attempting to run an RK4 (Runge-Kutta 4th order) on Newton's Cooling ODE for 5 terms for use in the Adams-Moulton Method. This is just a chunk of code, but my question has to do with the array declared before the while loop.

double tmpry[5];

This is declared, and then assigned values (the for loop here is for future implantation of multidimensional q, but for this it is only 1 dimension) for all 5 of its indices. As you can see I do a

cout << tmpry[j] << endl;

for debugging that appears twice in my code. I have labeled which one outputs what when i execute the code. My question is, why do the values assigned in the for loop not carry over to outside the for loop, even though I declared the variable outside of all loops. (i.e what is the scope of tmpry[] and why is it not globally declared?).

I should also mention this is a header file that gets compiled into a single binary, but there are no conflicting variable names, and as far as I know they wouldn't matter anyway.

//Open the output file.
ofstream amData;
amData.open("output/" + name + "_adam-moutlon.csv");

double tmpry[5];
//Calculate the first 4 terms required by adams-mouton using Runge-Kutta 4.
int j = 0;
while(j <= 4)
{
    amData << t;
    for(int i = 0; i < q.size(); ++i)
    {
        amData << "," << q[i];
        double k1 = -0.1*(q[i]-30);
        double k2 = -0.1*(q[i] + (h*0.5)*k1 - 30);
        double k3 = -0.1*(q[i] + (h*0.5)*k2 - 30);
        double k4 = -0.1*(q[i] + h*k3 - 30);

        q[i] = q[i] + (h/6)*(k1 + 2*k2 + 2*k3+ k4);     
        tmpry[j] = q[i]; //Assign a value to tmpry[j]
        cout << tmpry[j] << endl; //THIS PRINTS THE DESIRED VALUE
    }
    t += h;
    cout << tmpry[j] << endl; //THIS PRINTS 0
    j++ // time step
    amData << endl; // go to next line
}
j = 0;

Thank you for any help/advice/kindly telling me I'm a dummy.


Aucun commentaire:

Enregistrer un commentaire