[英]Simplify if-clauses when checking for range and setting default value
I have a function that converts a double
value into the sbyte
and returns its hex representation: 我有一个将double
值转换为sbyte
并返回其十六进制表示形式的函数:
string convertToSByte(double num, double factor)
{
double _Value = num * factor;
if (_Value > 127)
{
_Value = 127;
}
else if (_Value < -127)
{
_Value = -127;
}
return Convert.ToSByte(_Value).ToString("X2");
}
The calculated _Value
is supposed to be within the range of [-127 ; 127]
计算出的_Value
应该在[-127 ; 127]
范围内[-127 ; 127]
[-127 ; 127]
if not then these values have to be set as default. [-127 ; 127]
如果没有,则必须将这些值设置为默认值。
Question: How can these two if conditions and the setting of the default values be simplified? 问题:如何简化这两个条件和默认值的设置?
EDIT: 编辑:
I tried using the conditional operator ?
我尝试使用条件运算符?
but actually it is not much simpler (even a little harder to read) and also not really less code 但实际上并没有那么简单(甚至更难阅读),也没有真正减少代码
ps. ps。 This question serves more of an educational purpose. 这个问题更多的是出于教育目的。 To find a different way to check for ranges of a variable 查找检查变量范围的另一种方法
You could use Min
/ Max
您可以使用Min
/ Max
string convertToSByte(double num, double factor)
{
var value = Math.Min(127, Math.Max(-127.0, num * factor));
return Convert.ToSByte(value).ToString("X2");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.