Infinity in MSVC++

风流意气都作罢 提交于 2019-12-05 04:04:22

Use numeric_limits:

#include <limits>

float maxFloat = std::numeric_limits<float>::infinity();
peterchen

printf("%x\n", inf) expects an integer (32 bit on MSVC), but receives a double. Hilarity will ensue. Err, I mean: undefined behavior.

(And yes, it receives a double since for a variable argument list, floats are promoted to double).

Edit anyways, you should use numeric_limits, as the other reply says, too.

In the variable arguments list to printf, floats get promoted to doubles. The little-endian byte representation of infinity as a double is 00 00 00 00 00 00 F0 7F.

As peterchen mentioned, "%x" expects an int, not a double. So printf looks at only the first sizeof(int) bytes of the argument. No version of MSVC++ defines int to be larger than 4 bytes, so you get all zeros.

Take a look at numeric_limits::infinity.

That's what happens when you lie to printf(), it gets it wrong. When you use the %x format specifier, it expects an integer to be passed on the stack, not a float passed on the FPU stack. Fix:

printf( "%x\n", *(__int32*)&inf ) ;

You can get infinity out of the <limits> C++ header file:

float inf = std::numeric_limits<float>::infinity().
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!