On Sun, 07 Aug 2005 00:41:27 GMT,

al***@start.no (Alf P. Steinbach)

wrote:

* Code4u: In the course of writing numerical code I needed to convert a float to

an int with a defined behavior: if the float is great than INT_MAX,

set the int to INT_MAX, otherwise assign directly. The problem I ran

into is a float with value INT_MAX assigned to an int results in the

value -2147483648 being assigned, but if the conversion takes place in

an expression INT_MAX is assigned as I would expect:

int temp1=float(std::numeric_limits<int>::max()); // 2147483647

I think this may be computed at compile-time with 'double' precision.

float temp2=std::numeric_limits<int>::max(); //2.1474836e+009

int temp3=temp2; // -2147483648

Consider that in many current implementations an 'int' is 32 bits, and a

'float' is 32 bits. In the 'float' some bits are used for the exponent, so

there are far fewer than 32 bits in the mantissa, i.e. not enough to

represent an arbitrary 'int' value exactly.

My question: how do I write a function to trim a float to an int's

limits?

Off the cuff,

int intFromFloat( float f )

{

static int const max = std::numeric_limits<int>::max();

return 0?0

: f > max? max

: f < -max? -max

: static_cast<int>( f );

}

Thanks, yep, I should have spotted the compile-time conversion to

double.

One question, I don't quite understand the syntax of the ternary

conditional operator you used in the function, I've never seen 0?0 in

code before, could you elucidate?