如何在没有math.pow c#的情况下计算功率

时间:2018-01-07 13:31:18

标签: c#

我是C#的新人 我需要帮助来填写以下方法:

static double ToPower(double x,int n){

将数字x提升为整数幂n(即,计算值xn)。请记住,x-n = 1 / xn,x0 = 1。 我可以使用循环或递归可以有人帮助这个。

1 个答案:

答案 0 :(得分:0)

使用循环你可以这样做:

public double Pow(double num, int pow)
{
    double result = 1;

    if (pow > 0)
    {
        for (int i = 1; i <= pow; ++i)
        {
            result *= num;
        }
    }
    else if (pow < 0)
    {
        for (int i = -1; i >= pow; --i)
        {
            result /= num;
        }
    }

    return result;
}

使用enumerables你可以这样做:

using System.Collections;
using System.Collections.Generic;

...

public double Pow(double num, int pow)
{
    var sequence = Enumerable.Repeat(num, pow);

    if (pow > 0)
    {
        return sequence.Aggregate(1, (accumulate, current) => accumulate * current);
    }
    else if (pow < 0)
    {
        return sequence.Aggregate(1, (accumulate, current) => accumulate / current);
    }
    else
    {
        return 1;
    }
}