absolute value of an int is negative in template function!?

Jul 6, 2011 at 4:24am
Hi everyone,
I have a very large float that I want to convert to an int (by 'mod'ing it basically), but I noticed that the function wasn't working. I traced the problem to some very strange behaviour, which I have replicated below:

1
2
3
4
5
6
7
8
9
10
11
12

template <class _float>
int round_to_int (_float input) {
return abs( int(input + 0.5) );
}

int main() {

    float input = 1.121e18;
    cout << "\n" << int ( abs( int(input + 0.5) ) ); // returns 2147483647
    cout << "\n" << round_to_int<float>(input);      // returns -2147483648
}


why do these functions not return the same thing? (note that this program makes no sense, I've just stripped away everything that DID make sense in order to illustrate my problem). My program needs to return a positive integer (hence the abs() function) but this just doesn't seem to happen..
Jul 6, 2011 at 7:45am
That's weird. When I compile it with VC++ it gives the same (negative) number on both lines. That's because that number is too big to be stored in an integer. If you want to round a float, use floor(). If you want to convert that float into an integer, you'll have to use http://gmplib.org/ or something like that.
Jul 19, 2011 at 1:26am
Yeah that seems to be why, although I don't quite understand why the functions have different results. I suppose it's what you would call "undefined" behaviour... I fixed this problem by limiting the size of all int values to 2147483647. Another solution would just be to use unsigned integers, so in the worst case a number would bounce back to 0, which in my code wouldn't be a problem.

However I've left them as ints in my case because I want to know when this sort of thing happens (these numbers are all indices of arrays so I get a seg fault as soon as this happens).
Topic archived. No new replies allowed.