How do I calculate power-of in C#?

后端 未结 8 1563
别跟我提以往
别跟我提以往 2021-01-01 08:08

I\'m not that great with maths and C# doesn\'t seem to provide a power-of function so I was wondering if anyone knows how I would run a calculation like this:



        
8条回答
  •  执笔经年
    2021-01-01 08:56

    Following is the code calculating power of decimal value for RaiseToPower for both -ve and +ve values.

    public decimal Power(decimal number, decimal raiseToPower)
            {
                decimal result = 0;
                if (raiseToPower < 0)
                {
                    raiseToPower *= -1;
                    result = 1 / number;
                    for (int i = 1; i < raiseToPower; i++)
                    {
                        result /= number;
                    }
                }
                else
                {
                    result = number;
                    for (int i = 0; i <= raiseToPower; i++)
                    {
                        result *= number;
                    }
                }
                return result;
            }
    

提交回复
热议问题