Skip to content

Latest commit

 

History

History
64 lines (44 loc) · 1.38 KB

98.md

File metadata and controls

64 lines (44 loc) · 1.38 KB

C++ 程序:使用递归计算幂

原文: https://www.programiz.com/cpp-programming/examples/power-recursion

该程序使用递归来计算数字的幂,其中用户输入了底数和指数。

要理解此示例,您应该了解以下 C++ 编程主题:



示例:使用递归编程

#include <iostream>
using namespace std;

int calculatePower(int, int);

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

    cout << "Enter base number: ";
    cin >> base;

    cout << "Enter power number(positive integer): ";
    cin >> powerRaised;

    result = calculatePower(base, powerRaised);
    cout << base << "^" << powerRaised << " = " << result;

    return 0;
}

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

输出

Enter base number: 3
Enter power number(positive integer): 4
3^4 = 81

仅当指数为正整数时,此技术才能计算功效。

要查找任意数量的幂,可以使用pow()函数。

result = pow(base, exponent);