C++ 求一个数的幂程序

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


此程序从用户那里获取两个数字(基数和指数),并计算其幂。

Power of a number = baseexponent

示例 1:手动计算幂

#include <iostream>
using namespace std;

int main() 
{
    int exponent;
    float base, result = 1;

    cout << "Enter base and exponent respectively:  ";
    cin >> base >> exponent;

    cout << base << "^" << exponent << " = ";

    while (exponent != 0) {
        result *= base;
        --exponent;
    }

    cout << result;
    
    return 0;
}

输出

Enter base and exponent respectively:  3.4
5
3.4^5 = 454.354

 

如我们所知,一个数的幂是该数本身重复相乘。例如,

53 = 5 x 5 x 5 = 125

这里,5是基数,3是指数

在此程序中,我们使用while循环计算了数的幂。

while (exponent != 0) {
    result *= base;
    --exponent;
}

请记住,我们在程序开始时已将result初始化为1

让我们看看当base == 5exponent == 3时,此while循环如何工作。

迭代 result *= base exponent exponent != 0 执行循环?
第 1 次 5 3 true
第 2 次 25 2 true
第 3 次 125 1 true
第 4 次 625 0 false

但是,上述技术仅在指数为正整数时才有效。

如果你需要计算指数为任何实数时的数的幂,可以使用pow()函数。


示例 2:使用 pow() 函数计算幂

#include <iostream>
#include <cmath>

using namespace std;

int main() 
{
    float base, exponent, result;

    cout << "Enter base and exponent respectively:  ";
    cin >> base >> exponent;

    result = pow(base, exponent);

    cout << base << "^" << exponent << " = " << result;
    
    return 0;
}

输出

Enter base and exponent respectively:  2.3
4.5
2.3^4.5 = 42.44

在此程序中,我们使用了pow()函数来计算数的幂。

请注意,我们已包含cmath头文件以便使用pow()函数。

我们从用户那里获取baseexponent

然后,我们使用pow()函数来计算幂。第一个参数是基数,第二个参数是指数。


另请阅读

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来计算数字的幂。

  • 返回基数 raised to the exponent 的幂。
  • 幂的公式是:result = base ^ exponent
  • 例如,如果base = 2exponent = 3,返回值应为8
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战