Using NAN as not defined value

huangapple go评论77阅读模式
英文:

Using NAN as not defined value

问题

我正在开发一个C#项目,用于向用户显示一个双精度值。如果这个值未定义,我将显示一个空字符串。当值被定义时,它将大于或等于零。为了处理未定义的情况,我考虑是否可以定义一个超出范围的值,例如-1来表示未定义,或者将该值包装在一个具有布尔定义标志的类中。然后我想,为什么不直接使用Double.NAN来表示值未定义,然后使用Double.IsNAN来检查未定义的值呢?我认为这会起作用,但感觉有点不对。使用Double.NAN来表示未定义的值是一个好主意吗?

英文:

I am working on a CSharp project that displays a double value to the user. This value may not be defined in which case I will display an empty string. When the value is defined it will be greater than or equal to zero. To handle the not defined case, I thought I could define an out of range value, e.g. -1 to represent not defined or wrap the value in a class that has a boolean defined flag. Then I thought, why not just use Double.NAN to signify the value is not defined and Double.IsNAN to check for undefined values. I think this will work, but it just feels a bit wrong. Is it a good idea to use Double.NAN to represent an undefined value?

答案1

得分: 2

你可以使用现有包装器 Nullable<double>double?

double? d;

if (d.HasValue)
  Console.WriteLine($"{d.Value}");

Console.WriteLine($"{d.GetValueOrDefault(0)}"); // 如果值未定义,则会打印0

我认为这更合适,因为double.NaN 用于数学运算中的未定义结果情况。

英文:

you can use existing wrapper Nullable<double> or double?

double? d;

if (d.HasValue)
  Console.WriteLine($"{d.Value}");


Console.WriteLine($"{d.GetValueOrDefault(0)}"); // this will print 0 if value was not defined

It better suits I suppose since double.NaN is for result undefined cases for math operations

huangapple
  • 本文由 发表于 2020年1月6日 17:26:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定