代码之家  ›  专栏  ›  技术社区  ›  David Cournapeau

在windows上处理fpu异常

  •  2
  • David Cournapeau  · 技术社区  · 17 年前

    我想在windows上处理fpu异常,例如:

    #include <math.h>
    #include <fenv.h>
    #include <stdio.h>
    
    int main()
    {
        double b = 0;
        int raised;
        feclearexcept (FE_ALL_EXCEPT);
        b /= 0;
        raised = fetestexcept (FE_OVERFLOW | FE_INVALID);
        if (raised & FE_OVERFLOW) { printf("over\n");}
        if (raised & FE_INVALID)  { printf("invalid\n");}
    
        return 0;
    }
    

    我对C++中的异常不感兴趣,实际上,我对FPU异常甚至不感兴趣,只是在计算了FPU状态之后,如上面的例子。

    ==编辑==

    好的,看起来实际上要简单得多:使用_clearfp就足够了:

    #include <math.h>
    #include <float.h>
    #include <stdio.h>
    
    int main()
    {
        double b = 0;
        int raised;
        raised = _clearfp();
        b /= 0;
        raised = _clearfp();
        if (raised & SW_INVALID)  { printf("invalid\n");}
    
        return 0;
    }
    

    3 回复  |  直到 17 年前
        1
  •  2
  •   Hans Passant    17 年前

    #include "stdafx.h"
    #include <float.h>
    #include <math.h>
    #include <assert.h>
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
      unsigned x86;
      unsigned sse;
      // Test zero-divide
      double d = 0;
      double v = 1 / d;
      _statusfp2(&x86, &sse);
      assert(x86 & _EM_ZERODIVIDE);
      // Test overflow
      v = pow(10, 310.0);
      _statusfp2(&x86, &sse);
      assert(sse & _EM_OVERFLOW);
      return 0;
    }
    
        2
  •  2
  •   arul    17 年前

    如果是Visual Studio,请尝试插入以下行:

    #pragma   float_control (except, on)
    

    更多关于这个 here here .

    如果要在普通C中执行此操作,需要查看 structured exception handling ( SEH ).

        3
  •  0
  •   dirkgently    17 年前

    这些函数是标准强制要求的,因此在移植方面应该没有问题。你到底犯了什么错误?