我在 C# 中对 decimal
进行了简单的转换。它看起来像这样:
private decimal BaseValue
{
get; set;
}
public decimal ConvertedValue
{
get
{
return BaseValue * (365 / 360);
}
}
但是,这不起作用。我假设是因为 C# 正在将分数中的数字处理为整数。所以我可以这样做(有效):
public decimal ConvertedValue
{
get
{
return BaseValue * (decimal)((double)365 / (double)360);
}
}
现在这似乎有点矫枉过正,但我可以接受。我的主要问题是:
Why does Visual Studio warn me that 'Cast is redundant', for the
(double)
cast? And if I remove the(double)
cast, then the(decimal)
cast becomes redundant. And if I remove that, then I am back to the solution, which does not work. Help...?
最佳答案
解决这个问题的一种方法是指定计算中的数字是 decimal
并在末尾加上 m
return BaseValue * (365m / 360m);
Why does Visual Studio warn me that 'Cast is redundant', for the (double) cast
因为当等式的一侧有一个 double
时,结果将是一个 double。
(double)365 / (double)360
看看the documentation of the * operator overloads .您会看到操作数始终属于同一类型,例如:
decimal operator *(decimal x, decimal y);
... then the (decimal) cast becomes redundant.
同样,因为当你在等式的一侧有一个小数
时,结果将是一个小数:
BaseValue * (decimal)(365 / 360)
这里的问题是范围!您将除法的整个结果转换为 decimal
。其实你可以简单地通过删除括号来解决你的问题:
return BaseValue * 365 / 360;
这样你的等式将是正确的,因为 *
乘法的结果将是 decimal
(因为其中一个操作数是 decimal
,所以另一个将被隐式转换)并且出于同样的原因,除法的结果也将是小数。
注意: 删除括号通常与保留括号不同。在某些情况下,当此类运算的顺序发生变化时,浮点运算的结果会有所不同,即使这两个表达式在数学上是相同的。由 Banex 发表评论
编辑:
m
东西被称为文字。关于所有类型后缀或文字的更多信息可以在 documentation here 上找到
关于c# - 小数和数学运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46323299/