value of (int) casted double differs from the same value assigned to an integer

Hi,
well, the problem is not very easy to describe. Afaik, if you assign a double precision value to an integer it should be rounded down to it's closest integer value, so if I intend to only use the integer part of it I can as well do this from the beginning by assigning a double precision value to an integer instead of using c cast or c++ style casts later on. But then I wonder why on earth the following code provides unexpected results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cmath>
#include <iostream>
#include <string>
using namespace std;

void test(int index,  int base = 26)
{
    double n  = ((log10((index + 1) * (base - 1) + 1)) / log10(base));
    int n2 = ((log10((index + 1) * (base - 1) + 1)) / log10(base)); // DEBUG
    int n3 = n;
    
    if ((int) n != n2)
      printf("index: %d\tn: %f\t(int) n: %d\tn2: %d\tn3: %d\n", index, n, (int) n, n2, n3);
}

int main()
{
  for (int i = 0; i < 270; ++i)
     test(i, 2);
}


It's strange. If I assign the result of an expression which is of type double to a variable n of type double and then create a new integer variable n3 and assign the value of n to it, or use c style casts the result is ok (). But if I assign the result of the above mentioned expression to an integer variable n2 from the beginning, then the result is different as highlighted by the code. Why is that?

Thanks in advance,
momesana
You are having double precision errors.

What is probably happening is you are getting a number like 7.99999999999999..., which when you insert it into a double, it becomes 8.00000..., since it cannot hold that many digits, rounding them up, but when you directly insert it into an int, the computer still has all those extra digits in memory, so it can just chop off the .999999... and give you 7. Try looking at it through a debugger to check though.
I think it may also be compiler specific - as it happens in Mingw but not in MSVC
Thanks to both of you. I'll check it with a debugger. I am using it on gentoo linux using g++ and as far as I know mingw uses the GCC compiler suit as well so it may really have something to do with the compiler.
Last edited on
Just installed and tried the Intel C++ compiler and there are no issues there. Strange. Very strange.
Topic archived. No new replies allowed.