0

This is my ANSI C code.

int i,j;
float t,h;

i=30;
t=0.0;
h=0.1;

for(j=0; j <= i; j=j+1)
  {
    printf("time=%f\n",t);
    t=t+h;
  }

Output of the above code is:

time=0.000000
time=0.100000
time=0.200000
time=0.300000
time=0.400000
time=0.500000
time=0.600000
time=0.700000
time=0.800000
time=0.900000
time=1.000000
time=1.100000
time=1.200000
time=1.300000
time=1.400000
time=1.500000
time=1.600000
time=1.700000
time=1.800000
time=1.900000
time=2.000000
time=2.100000
time=2.200000
time=2.300000
time=2.400000
time=2.500000
time=2.600000
time=2.700000
time=2.799999
time=2.899999
time=2.999999
time=3.099999

Last four entries should be as follows:

time=2.800000

time=2.900000

time=3.000000

time=3.100000

But I get different values. Why so ? Any help will be highly appreciated.

atom
  • 153
  • 1
  • 9
  • 2
    Use double instead of float and you will get the expected result, this is related with float precision. Check this link for more information: http://stackoverflow.com/questions/5098558/float-vs-double-precision – aicastell Mar 23 '17 at 07:43
  • As this is the 2nd question about floating point values today, I recommend that you read up on how floating point math works. – Kami Kaze Mar 23 '17 at 09:03

0 Answers0