Here is my code:
#include <stdio.h>
int main()
{
float dt = 0.0002, t0;
int it0;
for ( t0 = 0.0512; t0 <= 0.0544; t0 += 0.0004 ) {
it0 = (int)(t0/dt);
printf("t0 = %f, it0 = %d\n",t0,it0);
}
return 0;
}
I run the above code, the result is:
t0 = 0.051200, it0 = 256
t0 = 0.051600, it0 = 258
t0 = 0.052000, it0 = 260
t0 = 0.052400, it0 = 262
t0 = 0.052800, it0 = 264
t0 = 0.053200, it0 = 265 --> Start to get wrong from here!
t0 = 0.053600, it0 = 267
t0 = 0.054000, it0 = 269
t0 = 0.054400, it0 = 271
When t0 = 0.053200
, it0
should be 266
(0.0532/0.0002=266). But here it shows it0 = 265
. To investigate the reason, I run t0 = 0.053200
independently as follows:
#include <stdio.h>
int main()
{
float dt = 0.0002, t0 = 0.0532;
int it0;
it0 = (int)(t0/dt);
printf("t0 = %f, it0 = %d\n",t0,it0);
return 0;
}
The result is correct:
t0 = 0.053200, it0 = 266
I don't know why it happens. So I do another test which prints the float (before converting) and integer (after converting) using code below:
#include <stdio.h>
int main()
{
float dt = 0.0002, t0, test;
int it0;
for ( t0 = 0.0512; t0 <= 0.0544; t0 += 0.0004 ) {
it0 = (int)(t0/dt);
test = t0/dt;
printf("t0 = %f, it0 = %d / %f\n",t0,it0,test);
}
return 0;
}
The result is:
t0 = 0.051200, it0 = 256 / 256.000000
t0 = 0.051600, it0 = 258 / 258.000000
t0 = 0.052000, it0 = 260 / 260.000000
t0 = 0.052400, it0 = 262 / 262.000000
t0 = 0.052800, it0 = 264 / 264.000000
t0 = 0.053200, it0 = 265 / 265.999969
t0 = 0.053600, it0 = 267 / 267.999969
t0 = 0.054000, it0 = 269 / 269.999969
t0 = 0.054400, it0 = 271 / 271.999969
I notice that t0 = 0.053200, it0 = 265 / 265.999969
. I guess the convert to integer makes 265.999969
a wrong number which is 265
. Do you know how to solve it?