无符号双人

Ami*_*Raz 29 c# double unsigned

我需要使用unsigned double,但事实证明C#不提供这样的类型.

有谁知道为什么?

And*_*ren 17

浮点数只是IEEE 754规范的实现.据我所知,在那里没有无符号的双子.

http://en.wikipedia.org/wiki/IEEE_754-2008

为什么需要无符号浮点数?

  • @Backwards_Dave这是一个很好的问题.我不负责任,当时我7岁:D (14认同)
  • 使用运行时检查,或丢弃符号(使用Math.Abs​​(arg))或尝试代码契约,或将参数类型更改为强制执行约束的类/结构.我建议在传递负参数时抛出异常(contractexception是个好主意),或者如果可以安全地丢弃符号,例如 (5认同)
  • 我需要能够传递一个变量,它可以是一个分数,必须是正数.我想在我的Function签名中使用它来强制执行它. (4认同)
  • 如果有一个uint等,为什么htey没有做一个unsigned double?那么你就不必在上面的评论@AndersForsgren中提到你提到的所有内容 (4认同)

Isa*_*avo 17

正如Anders Forsgren所指出的那样,IEEE规范中没有未签名的双精度数据(因此不在C#中).

您可以通过调用Math.Abs​​()来获得正值,并且可以在结构中包含double并在那里强制执行约束:

public struct PositiveDouble 
{
      private double _value;
      public PositiveDouble() {}
      public PositiveDouble(double val) 
      {
          // or truncate/take Abs value automatically?
          if (val < 0)
              throw new ArgumentException("Value needs to be positive");
          _value = val;
      }

      // This conversion is safe, we can make it implicit
      public static implicit operator double(PositiveDouble d)
      {
          return d._value;
      }
      // This conversion is not always safe, so we make it explicit
      public static explicit operator PositiveDouble(double d)
      {
          // or truncate/take Abs value automatically?
          if (d < 0)
              throw new ArgumentOutOfRangeException("Only positive values allowed");
          return new PositiveDouble(d);
      }
      // add more cast operators if needed
}
Run Code Online (Sandbox Code Playgroud)

  • +1 用于列出实现所需行为的多种方法 (3认同)