MSVC++中的无限

bob*_*obo 8 c++ floating-point infinity visual-c++

我正在使用MSVC++,我想在我的代码中使用特殊值INFINITY.

MSVC++中无限使用的字节模式或常量是什么?

为什么1.0f/0.0f似乎值为0?

#include <stdio.h>
#include <limits.h>

int main()
{
  float zero = 0.0f ;
  float inf = 1.0f/zero ;

  printf( "%f\n", inf ) ; // 1.#INF00
  printf( "%x\n", inf ) ; // why is this 0?

  printf( "%f\n", zero ) ; // 0.000000
  printf( "%x\n", zero ) ; // 0

}
Run Code Online (Sandbox Code Playgroud)

GMa*_*ckG 20

用途numeric_limits:

#include <limits>

float maxFloat = std::numeric_limits<float>::infinity();
Run Code Online (Sandbox Code Playgroud)


pet*_*hen 11

printf("%x\n", inf)期望一个整数(MSVC上为32位),但接收一个double.随之而来的是欢闹.呃,我的意思是:未定义的行为.

(是的,它收到一个双倍,因为对于一个变量参数列表,浮点数被提升为double).

无论如何编辑,你应该使用numeric_limits,正如其他回复所说的那样.