gpt4 book ai didi

c# - Double.MaxValue 为整数是否为负数?

转载 作者:IT王子 更新时间:2023-10-29 04:31:00 24 4
gpt4 key购买 nike

为什么 Double.MaxValue转换为整数类型会产生负值,即该类型的最小值?

double maxDouble = double.MaxValue;       // 1.7976931348623157E+308
long maxDoubleLong = (long) maxDouble; // -9223372036854775808

如果它太大或在运行时出现 OverflowException,或者如果我使用 unchecked 转换可能不会引发异常,我会理解编译器错误,但是结果变得不确定和不正确(负)。

同样奇怪的是,这个值是long.MinValue :

bool sameAsLongMin = maxDoubleLong == long.MinValue; // true

顺便说一句,如果我将它转换为 int,也会发生同样的情况:

int maxDoubleInt = (int)maxDouble;                   // -2147483648
bool sameAsIntMin = maxDoubleInt == int.MinValue; // true

如果它尝试将其转换为decimal,我会在运行时得到一个OverflowException

decimal maxDoubleDec = (decimal)maxDouble;  // nope

更新:Michael 和 Barre 的回答似乎一针见血,如果我明确使用 checked,我会得到一个 OverflowException:

checked
{
double maxDouble = double.MaxValue; // 1.7976931348623157E+308
long maxDoubleLong = (long) maxDouble; // nope
}

最佳答案

C# Language Specification(5.0 版)在 6.2.1“显式数字转换”(添加了强调)中说明如下:

  • For a conversion from float or double to an integral type, the processing depends on the overflow checking context (§7.6.12) in which the conversion takes place:

    • In a checked context, the conversion proceeds as follows:

      • If the value of the operand is NaN or infinite, a System.OverflowException is thrown.
      • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.
      • Otherwise, a System.OverflowException is thrown.
    • In an unchecked context, the conversion always succeeds, and proceeds as follows.

      • If the value of the operand is NaN or infinite, the result of the conversion is an unspecified value of the destination type.
      • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.
      • Otherwise, the result of the conversion is an unspecified value of the destination type.

以及在 7.6.12“已检查和未检查的运算符”中

For non-constant expressions (expressions that are evaluated at run-time) that are not enclosed by any checked or unchecked operators or statements, the default overflow checking context is unchecked unless external factors (such as compiler switches and execution environment configuration) call for checked evaluation.

对于从 doubledecimal 的转换:“如果源值为 NaN、无穷大或太大而无法表示为小数,则抛出 System.OverflowException” . checked vs unchecked 没有发挥作用(那些只处理积分运算)。

关于c# - Double.MaxValue 为整数是否为负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22757239/

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