C
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
float temp2=std::numeric_limits<int>::max(); //2.1474836e+009
int temp3=temp2; // -2147483648
My question: how do I write a function to trim a float to an int's
limits?
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
float temp2=std::numeric_limits<int>::max(); //2.1474836e+009
int temp3=temp2; // -2147483648
My question: how do I write a function to trim a float to an int's
limits?