c# - 除以零奇数

标签 c#

我今天遇到了一个问题,我不小心被零除,但没有抛出异常。当我使用调试器时,我在调试器中看到“NaN”。当我尝试使用 NUnit 重新创建此场景时,Assert 说我正在返回“Infinity”。不能完全让调试器显示 NaN,但我只是想知道为什么在这种情况下没有抛出错误?我花了很长时间才找到这个问题,我会认为应该抛出异常吗?

测试代码如下:

public class DivideByZero {

    private int TotalQaOneToFour;
    private int TotalGrade = 10;

    public DivideByZero(int TotalQaOneToFour) {
      this.TotalQaOneToFour = TotalQaOneToFour;
    }

    public Double QualityReportAverageRounded {
      get {
        return Math.Round((double)TotalGrade / TotalQaOneToFour, 2);
      }
    }
  }


  [TestFixture]
  public class DivideByZeroTest {

    [Test]
    public void TestThatDivideByZeroThrowsWhenUsingMathRound() {

      var dbz = new DivideByZero(0);

      Assert.AreEqual(0, dbz.QualityReportAverageRounded);
    }

  }

这是 NUnit 输出:

Test 'DivideByZeroTest.TestThatDivideByZeroThrowsWhenUsingMathRound' failed:
Expected: 0
But was: Infinity
DivideByZero.cs(33,0): at DivideByZeroTest.TestThatDivideByZeroThrowsWhenUsingMathRound()

0 passed, 1 failed, 0 skipped, took 0.41 seconds (NUnit 2.6.1).

最佳答案

Can't quite get the debugger to display the NaN, but I'm just wondering why there is no error thrown in this case?

因为这会违反规范 :) 基本上,这里没有必要抛出异常,因为 IEEE-754 a) 定义了除以 0 的处理方式; b) 对于除以 0 的结果具有适当的值。对于整数类型(和 decimal),这些都不是真的,这就是你得到 DivideByZeroException 的地方。

如果您将任何非零、非 NaN 值除以零,您应该得到无穷大(正或负)。如果您将零(或 NaN)除以零,您应该得到 NaN。

示例代码:

using System;

class Test
{
    static void Main()
    {
        // Prevent everything being computed at compile-time
        double zero = 0d;
        Console.WriteLine(1d / zero);  // Infinity
        Console.WriteLine(0d / zero);  // NaN
        Console.WriteLine(-1d / zero); // -Infinity
    }
}

来自 C# 5 规范第 7.8.2 节(其他编号适用于其他版本):

Integer division

[...]
If the value of the right operand is zero, a System.DivideByZeroException is thrown.
[...]

Floating point division

The quotient is computed according to the rules of IEEE 754 arithmetic. The following table lists the results of all possible combinations of nonzero finite values, zeros, infinities, and NaN’s.

(然后有一个表格给出了与我之前描述的相同类型的结果。)

关于c# - 除以零奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283082/

相关文章:

c# - 可空类型 : better way to check for null or zero in c#

c# - .Net Core Strings.Asc/Mid/Chr/Len 即使在导入 Microsoft.VisualBasic 后也丢失

c# - 将数据保存在可执行文件中

c# - Unity 和 NUnit

c# - "official"语言开发者使用了哪些编译器工具?

c# - 如何使用imdisk和C#创建RAM磁盘?

c# - 这个带有 "arrow"的 C# 代码是什么意思,它是如何调用的?

c# - 如何在C#中使组合框在鼠标悬停时自动展开并在鼠标离开组合框时关闭?

C# 与 PHP 脚本通信时无法创建 SSL/TLS 安全通道异常

c# - 在 C# 中是否可以检查给定的日期格式字符串是否仅包含日期格式或时间格式?