计算数字次方的 C++ 程序
在本文中,我们将学习手动计算一个数字的次方,和使用 pow()
函数计算一个数字的次方。
要理解此示例,您应该具备以下 C++ 编程 主题的知识:
该程序从用户那里获取两个数字(一个基数和一个指数)并计算次方。
示例 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
。
让我们看看如果 base == 5
和 exponent == 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()
函数来计算一个数的次方。
请注意,为了使用 pow()
函数,我们已经包含了头文件 cmath
。
我们让用户输入 base
和 exponent
。
然后我们使用 pow()
函数来计算次方。第一个参数是 base
,第二个参数是 exponent
。