无法理解其工作原理

时间:2019-01-22 18:20:00

标签: c recursion

据我所知,我不理解这一点;

4 * 4 ^ 2 * 4

但是它没有,我知道它有一个简单的解释,但我仍然试图在20分钟内弄清楚这一点,希望有人能帮上忙。不好意思,编辑也很抱歉。

int power(int n1, int n2);

int main() {
    int base, powerRaised, result;

    printf("Enter base number: ");
    scanf("%d", &base);

    printf("Enter power number(positive integer): ");
    scanf("%d", &powerRaised);

    result = power(base, powerRaised);

    printf("%d^%d = %d", base, powerRaised, result);
    return 0;
}

int power(int base, int powerRaised) {
    if (powerRaised != 0)
        return (base * power(base, powerRaised - 1));
    else
        return 1;
}

1 个答案:

答案 0 :(得分:0)

代码的行为符合预期,power函数是递归的。对于参数42,它递归调用两次:

   power(4, 2)
-> 4 * power(4, 1)
-> 4 * (4 * power(4, 0))
-> 4 * (4 * 1)
-> 16

您可能更熟悉迭代方法:

int power(int base, int powerRaised) {
    int res = 1;
    while (powerRaised > 0) {
        res = res * base;
        powerRaised--;
    }
    return res;
}