1

consider the following program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
  int i;
  long int rr;
  double   dd;
  double arr[10] = {55.550,55.551,55.552,55.553,55.554,55.555,55.556,55.557,55.558,55.559};
  printf("\n\nTest1");
  for(i=0;i<10;i++)
  {
    dd = 100 * arr[i];
    rr = (long int)dd;
    printf("\n 100 * %10.4lf == %10.4lf >>>>> %ld",arr[i], dd, rr);
  }
  printf("\n\nTest2");
  for(i=0;i<10;i++)
  {
    printf("\n 100 * %10.4lf == %10.4lf >>>>> %ld",
           arr[i], 100 * arr[i], (long int)(100 * arr[i]));
  }
  return 0;
}

After I execute this thing I got:

Test1
 100 *    55.5500 ==  5555.0000 >>>>> 5555
 100 *    55.5510 ==  5555.1000 >>>>> 5555
 100 *    55.5520 ==  5555.2000 >>>>> 5555
 100 *    55.5530 ==  5555.3000 >>>>> 5555
 100 *    55.5540 ==  5555.4000 >>>>> 5555
 100 *    55.5550 ==  5555.5000 >>>>> 5555
 100 *    55.5560 ==  5555.6000 >>>>> 5555
 100 *    55.5570 ==  5555.7000 >>>>> 5555
 100 *    55.5580 ==  5555.8000 >>>>> 5555
 100 *    55.5590 ==  5555.9000 >>>>> 5555

Test2
 100 *    55.5500 ==  5555.0000 >>>>> 5554 <-- Look at here !
 100 *    55.5510 ==  5555.1000 >>>>> 5555
 100 *    55.5520 ==  5555.2000 >>>>> 5555
 100 *    55.5530 ==  5555.3000 >>>>> 5555
 100 *    55.5540 ==  5555.4000 >>>>> 5555
 100 *    55.5550 ==  5555.5000 >>>>> 5555
 100 *    55.5560 ==  5555.6000 >>>>> 5555
 100 *    55.5570 ==  5555.7000 >>>>> 5555
 100 *    55.5580 ==  5555.8000 >>>>> 5555
 100 *    55.5590 ==  5555.9000 >>>>> 5555
Process returned 0 (0x0)   execution time : -0.000 s
Press any key to continue.

Seems like when you multiply like this and then cast 55.550 the last digit is missed. Is that normal ?

How the casting should be preceded in that case ?

Shoe
  • 74,840
  • 36
  • 166
  • 272
  • 5
    It's actually 5554.99999999 but you are only using 4 decimal places precision so it gets rounded to 5555. Conversion to integer rounds down so 5554.99999999 goes to 5554. To avoid this you could use the `round` function, or add a small amount to the number before truncating. – M.M Jul 16 '15 at 13:52
  • On coliru it looks ok: http://coliru.stacked-crooked.com/a/2c39ce4f356a0345 -- what compiler are you using? – foraidt Jul 16 '15 at 13:52
  • The machine that this is actually running is based on Pro*C so std:... can not apply ... :) – Деян Добромиров Jul 16 '15 at 13:55
  • Just inserted it like that before you know it... anyways the pb should be the same – Деян Добромиров Jul 16 '15 at 13:57

1 Answers1

1

It is a standard problem of float precision. The value of 55.550 can not be stored in memory exactly, so some different but very close value is stored. So different sequences of operations (including even storing intermediate results into double) can affect the outcome. It may well be that on first test, the value in dd becomes 5555, while in the second case 100 * arr[i] becomes, say, 5554.9999999997.

Petr
  • 9,812
  • 1
  • 28
  • 52