首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >_controlfp不能阻止DivideByZeroException

_controlfp不能阻止DivideByZeroException
EN

Stack Overflow用户
提问于 2015-06-02 09:21:03
回答 1查看 431关注 0票数 0

我用C#写了以下几行

代码语言:javascript
复制
using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Program
    {
        [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
        extern static uint _controlfp(uint newcw, uint mask);

        const uint _MCW_EM = 0x0008001f;
        public const uint EM_INVALID = 0x00000010;
        public const uint EM_DENORMAL = 0x00080000;
        public const uint EM_ZERODIVIDE = 0x00000008;
        public const uint EM_OVERFLOW = 0x00000004;
        public const uint EM_UNDERFLOW = 0x00000002;
        public const uint EM_INEXACT = 0x00000001;

        static void MaskFpu(uint pExceptionMask = EM_INVALID)
        {
            // add desired values
            _controlfp(_MCW_EM, pExceptionMask);
        }

        static void Main(string[] args)
        {
            MaskFpu(EM_ZERODIVIDE);

            int a = 0;
            var b = 5/a;

            Console.WriteLine("b = " + b);
        }
    }
}

主要方法从设置控制字开始。显然,我想让DivideByZeroExceptions蒙上面具。

在执行_controlfp之后,我希望除以零将返回NaN。但是var b = 5 / a却引发了一个异常。

我如何才能真正地阻止我的过程提高DivideByZeroExceptions?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-02 09:54:52

代码语言:javascript
复制
int a = 0;
var b = 5/a;

您在这里执行整数运算,因此掩蔽浮点异常对此表达式没有任何影响。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30592060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档