One operator seems to be produce wrong results in my C code. First of all, these are the lines of my code where I declare the variables (outside the main function, general scope):
FILE *fenergy;
float p1,p2,p3;
float FinalEnergy, EnergyState;
Then, I call a function that performs sequentially the next lines of code:
p1=FinalEnergy;
p2=EnergyState;
FinalEnergy=FinalEnergy+EnergyState;
fprintf(fenergy,"p1=%f p2=%f Final=%f",p1,p2,FinalEnergy);
The file "fenergy" is correctly started by using the funcion:
fenergy=fopen(energy.txt,"w");
The values of all the variables seem to be correct in the first million of steps but then, the operation "+" in the line:
FinalEnergy=FinalEnergy+EnergyState;
Gives a wrong output. This is a sample of the results output from the file written by the fprintf function:
p1=-130482984.000000 p2=-23.000000 Final=-130483008.000000
p1=-130483008.000000 p2=-23.000000 Final=-130483032.000000
p1=-130483032.000000 p2=-24.000000 Final=-130483056.000000
I am getting crazy about this wrong result. There are only a sum operator and three variables, but my code gives that mistaken output. I have compiled and run my code in both windows 10 (MinGW) and linux (gcc).
I am really lost about this issue. Any suggestion would be highly appreciated.