-4

I need to write a recursive method Power(base, exponent) that, when called, returns Power(3,4) = 3*3*3*3. And exponent is an integer greater than or equal to 1. Below is my code, but it is wrong. I want to use factorial, but i know little about factorial.

public static void Main(string[] args)
{
    Console.WriteLine("please enter base,\n" + "please enter exponent,\n" + "pressing 'Enter'after each one");

    double number1 = Convert.ToDouble(Console.ReadLine());

    int number2 = Convert.ToInt16(Console.ReadLine());

    double result = Pow(number1, number2);

    Console.WriteLine("pow({0},{1}) is {2}",number1,number2,result);
}

public static long Factorial(long number)
{
    if (number <= 1)
        return 1;
    else
        return number * Factorial(number - 1);
}

public static double Pow(double basevalue, int exponentvalue)
{
    double a=1;
    if (exponentvalue==1)
    {
        Console.WriteLine("It is not make sense!");
        return basevalue;
    }
    else if(exponentvalue > 1)
    {
        a=exponentvalue * Factorial(exponentvalue - 1);
    }
    return a;
}
4

3 回答 3

4

我假设您谈论阶乘的原因是因为它可以使用递归算法计算,因此可以计算数字的整数幂。除此之外,您不应使用阶乘来计算功率。

要使用递归计算数字的幂,您可以这样做:

Power(base, exponent) = base*Power(base, exponent - 1)

并终止递归:

Power(base, 0) = 1

Power(3, 4)使用递归计算的结果如下:

Power(3, 4)
    = 3*Power(3, 3)
    = 3*3*Power(3, 2)
    = 3*3*3*Power(3, 1)
    = 3*3*3*3*Power(3, 0)
    = 3*3*3*3*1

在 C# 中实现这一点留作练习。

于 2013-02-02T20:49:56.420 回答
2

简单的。如果需要,您可以添加一些额外的无效检查exponentvalue

public static double Pow(double basevalue, int exponentvalue)
{
    if (exponentvalue == 0)
    {
        return 1;
    }
    if (exponentvalue == 1)
    {
        return baseValue;
    }
    return baseValue * Pow(basevalue, exponentvalue-1);
}
于 2013-02-02T20:45:31.177 回答
1

首先,您需要查找一些您正在使用的功能 mate。阶乘与权力无关。您可以将幂编写为递归函数,如下所示:

internal static double Pow(double @base, int exponent)
{
    if (exponent < 0)
    {
        Console.Error.WriteLine("Usage of this function is limited to positive exponents only");
        throw new Exception();
    }
    else if (exponent == 1)
    {
        return @base;
    }
    else if (exponent == 0)
    {
        return 1;
    }
    else
    {
        return @base * Pow(@base, exponent - 1);
    }
}
于 2013-02-02T20:50:00.020 回答