这个程序从用户那里获取两个数字(一个基数和一个指数)并计算幂。
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 == 5
和
exponent == 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
头文件。
我们从用户那里获取
base 和
exponent。
然后我们使用
pow()
函数来计算功率。第一个参数是底数,第二个参数是指数。