问题
As the title says, the functionality I'm after is provided by C++11's math libraries to find the next floating point value towards a particular value.
Aside from pulling the code out of the std library (which I may have to resort to), any alternatives to do this with C++03 (using GCC 4.4.6)?
回答1:
Platform dependently, assuming IEEE754, and modulo endianness, you can store the data of the floating point number in an integer, increment by one, and retrieve the result:
float input = 3.15;
uint32_t tmp;
unsigned char * p = reinterpret_cast<unsigned char *>(&tmp);
unsigned char * q = reinterpret_cast<unsigned char *>(&input);
p[0] = q[0]; p[1] = q[1]; p[2] = q[2]; p[3] = q[3]; // endianness?!
++tmp;
q[0] = p[0]; q[1] = p[1]; q[2] = p[2]; q[3] = p[3];
return input;
Beware of zeros, NaNs and infinities, of course.
来源:https://stackoverflow.com/questions/16335992/alternative-to-c11s-stdnextafter-and-stdnexttoward-for-c03