计算负数的幂 [英] Calculate power of a negative number
问题描述
我对C#相对较新,由于Math.Pow(x,y)返回负数的NaN(读:不是负幂),所以我想知道如何更有效地计算结果.我现在正在写的内容是一个基本的for循环,但是我想知道它是否可以以更短的方式实现(也许使用Linq)?
I relatively new to C# and since Math.Pow(x,y) returns NaN for a negative number(read: not negative power), I want to know how to calculate result more efficiently. What I am doing write now is a basic for loop, but I want to know if it can be implemented in shorter way (using Linq maybe)?
for(int i=0;i<power;i++)
{
result = result * num;
}
推荐答案
Math.Pow(x,y)
返回NaN
为负数.
那是因为没有为负数基定义任意幂:
That's because arbitrary exponentiation is not defined for a negative base:
http://en.wikipedia.org/wiki/Exponentiation
当基数b为正实数时,可以通过指数函数为所有实数甚至复数指数n定义b到n的值
when the base b is a positive real number, b to the n can be defined for all real and even complex exponents n via the exponential function
现在,如果幂是整数(如您的情况),则定义了负数的幂以得到真实的结果,但是Pow
不会为您计算它.您应该做的是:
Now, exponentiation of negative numbers to get a real result is defined if the power is an integer, as in your case, but Pow
will not calculate it for you. What you should do is:
- 假设您想了解
Pow(-2, 5)
- 改为
Pow
问题Pow(2, 5)
. - 看看指数;如果它是偶数,那么您将得到正确的答案.如果它是一个奇数,则答案是否定的.
- Suppose you want to know
Pow(-2, 5)
- Give
Pow
the problemPow(2, 5)
instead. - Look at the exponent; if it is an even number then you've got the right answer. If it is an odd number, then make the answer negative.
因此,在这种情况下,Pow(2, 5)
返回32.指数5为奇数,因此将其设为-32,就可以了.
So in this case, Pow(2, 5)
returns 32. The exponent 5 is odd, so make it -32, and you're done.
这篇关于计算负数的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!