用 C++ 编写一个程序来计算 pow(x,n)
在这个问题中,给定两个整数 x 和 n。我们的任务是编写一个程序来计算 pow(x,n)。
我们举个例子来理解这个问题。
输入
x = 5 , n = 3
输出
125
计算 pow(x,n) 的程序如下,
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include <iostream> using namespace std; float myPow(float x, int y) { if(y == 0) return 1; float temp = myPow(x, y / 2); if (y % 2 == 0) return temp*temp; else { if(y > 0) return x*temp*temp; else return (temp*temp)/x; } } int main() { float x = 5; int n = 7; cout<<x<<" raised to the power "<<n<<" is "<<myPow(x, n); return 0; }
输出
5 raised to the power 7 is 78125
该程序通过将指数分成两半,然后乘以两个一半,并考虑到负值,展示了一种有效的方法。
广告