And*_*ren 17
浮点数只是IEEE 754规范的实现.据我所知,在那里没有无符号的双子.
http://en.wikipedia.org/wiki/IEEE_754-2008
为什么需要无符号浮点数?
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)
| 归档时间: |
|
| 查看次数: |
20735 次 |
| 最近记录: |