原文: https://www.programiz.com/cpp-programming/examples/power-number
要理解此示例,您应该了解以下 C++ 编程主题:
该程序从用户处获得两个数字(一个基本数字和一个指数)并计算功效。
Power of a number = baseexponent
#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
仅当指数为正整数时,以上技术才有效。
如果需要以任何实数为指数的整数幂,可以使用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