计算负数的幂 [英] Calculate power of a negative number

查看:131
本文介绍了计算负数的幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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 problem Pow(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆