简体   繁体   English

Math.Pow(10,Math.Abs​​(1))等于10吗?

[英]Is Math.Pow(10, Math.Abs(1)) equal to 10?

I'm currently maintaining a code of a former colleague, and found following code (example): 我目前正在维护一个前同事的代码,并发现以下代码(示例):

double someValue = 20, someResult;

someResult = (Convert.ToInt32(Math.Round(someValue / (Math.Pow(10, Math.Abs(1))), MidpointRounding.AwayFromZero) * Math.Pow(10, Math.Abs(1))) + 10) - someValue;

and i wonder, why he used Math.Pow(10, Math.Abs(1)) instead of 10 ? 我不知道为什么他使用Math.Pow(10, Math.Abs(1))而不是10 Is it because of inaccuracy or some sort of? 是因为不准确还是某种原因?

The result is the same, if the code is changed to: 如果代码更改为:结果是相同的:

someResult = (Math.Round(someValue / 10, MidpointRounding.AwayFromZero) * 10 + 10) - someValue;

The only difference between using 10 instead of (Math.Pow(10, Math.Abs(1)) will be the type. If you write 10 in code the compiler will treat the number as an int . Math.Pow however will return a double . 使用10代替(Math.Pow(10, Math.Abs(1))的唯一区别是类型。如果在代码中写入10 ,编译器会将数字视为int但是Math.Pow将返回a double

Sometimes this could make a difference. 有时这可能会有所作为。 For example if someValue was an int then someValue/10 would be using integer division and thus might not do what you expect. 例如,如果someValue是一个intsomeValue/10将使用整数除法,因此可能无法达到您的期望。 In this case though someValue is a double so you will use floating point division either way. 在这种情况下,尽管someValuedouble someValue的,所以您将以任何一种方式使用浮点除法。

So yes, you are safe here replacing the Math.Pow call with just 10 . 所以是的,您可以放心地用10代替Math.Pow调用。

As for why it is like this - most often I find this sort of code exists because it was originally more complicated and then got simplified. 至于为什么这样-我经常发现这种代码存在是因为它本来更复杂,然后又简化了。 eg it might have originally been something like Math.Pow(10,precision) or something like that which needed the method call. 例如,最初可能是Math.Pow(10,precision)东西,或者可能需要方法调用的东西。 Then somebody decided to always make precision 1 and updated accordingly without actually simplifying any code such as this that could be simplified. 然后,有人决定始终使精度为1并相应地进行更新,而实际上并未简化任何可以简化的代码。

The actual why is pure speculation though. 实际的原因虽然是纯粹的猜测。 If this is in source control there might be a commit comment that explains it or if not it might allow you to find the author and ask them... 如果这在源代码管理中,则可能会有一个提交注释对此进行解释,否则,您可能会找到作者并询问他们...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM