gpt4 book ai didi

c# - 除以零奇数

转载 作者:太空狗 更新时间:2023-10-30 00:05:16 28 4
gpt4 key购买 nike

我今天遇到了一个问题,我不小心被零除,但没有抛出异常。当我使用调试器时,我在调试器中看到“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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com