C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ 计算数字幂的程序

计算一个数的幂的C++程序

在本文中,我们将学习手动计算一个数的幂,并使用 pow() 函数。
要理解此示例,您应该了解以下C++ 编程 主题:
C++ while 和 do...while 循环
这个程序从用户那里获取两个数字(一个基数和一个指数)并计算幂。
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
众所周知,一个数的幂是这个数反复乘以它自己。例如,
5 3 = 5 x 5 x 5 = 125
这里,5 是底数,3 是指数。
在这个程序中,我们使用 while 循环计算了一个数的幂。
while (exponent != 0) {
    result *= base;
   --exponent;
}
记住我们在程序开始时已经将 result初始化为 1
让我们看看这个 while 循环在 base == 5exponent == 3 的情况下是如何工作的。
迭代 结果 *= 基数 指数 指数 != 0 执行循环?
第一个 5 3 true
第二个 25 2 true
第三个 125 1 true
第四个 625 0 没有
然而,上述技术仅适用于指数为正整数的情况。
如果需要求以任意实数为指数的数的幂,可以使用 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() 函数来计算一个数的幂。
请注意,为了使用 pow() 函数,我们包含了 cmath 头文件。
我们从用户那里获取 baseexponent
然后我们使用 pow() 函数来计算功率。第一个参数是底数,第二个参数是指数。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4