Search code examples
cfunctionreturnreturn-value

C:Way to remove multiple values from a loop in a function


I need to create a file ie : Earth.txt, then put in multiple x and y coordinates from a loop, then close the file before opening a new file ie: Mars.txt with new boundary conditions and repeating (ideally without putting the creation of the file in the loop, else id have to change the name manually each time to stop it overriding the previous data).

I can't find a way to return the values into my main body of code and put them in the file. If I use return x or return y it gives me the last value whether inside or outside of the loop.

int main (){
    //Earth

    float ex = -147095000000, ey = 0, evx0 = 0, evy0 = -30300.0;

    FILE*outfile;
    outfile=fopen("Earth.txt", "w");
    Integration(ex, ey, evx0, evy0);
    fprintf(outfile,"This is x:%f\n",x);
    fclose(outfile);
}

And this is the function I need to extract my x values from:

float Integration(int *x, int *y, float vx0, float vy0){

    double k_1_x, k_2_x, k_1_y, k_2_y, k_1_vx ,k_1_vy, k_2_vx, k_2_vy;
    double dt = 86400; //seconds per day

    int i;

    for (i=0;i<800;i++){
        k_1_x = vx0;
        k_1_y = vy0;

        printf("x1:%f\ny1:%f\nvx1:%f\nvy1%f\n", *x, *y, vx0, vy0);

        return X;
    }

    return 0;
}

I should basically end up with 800 different x values printed into my file.


Solution

  • This

    for (i = 0; i < 800; i++) {
        // ...
        return X;  // <- Unconditioned
    }
    

    Is not a loop. The body will be executed only once and a single value (whatever X is) is returned (and ignored by the rest of the posted code, BTW).

    If I have understood the task you are trying to accomplish, you might change the function into something like this

    void Integration(FILE *out, double x0, double y0, double vx0, double vy0)
    {
        double k_1_x, k_2_x, k_1_y, k_2_y, k_1_vx ,k_1_vy, k_2_vx, k_2_vy;
        double x = x0, y = y0, vx = vx0, vy = vy0;
        // ...
    
        for (int i = 0; i < 800; ++i)
        {
            // Update the variables x, y, vx, vy...
            fprintf(out, "%lf %lf %lf %lf\n", x, y, vx, vy);
            //             ^^ Use the correct format specifier for doubles
        }
    }
    

    Also you should change the main into

    int main(void)
    {
        //Earth
        double ex = -147095000000, ey = 0, evx0 = 0, evy0 = -30300.0;
    
        FILE *outfile = fopen("Earth.txt", "w");
        if (!outfile)
            // Deal with the error
    
        Integration(outfile, ex, ey, evx0, evy0);
        fclose(outfile);
        // ...
    }