编写程序以在C ++中计算pow(x,n)
在这个问题上,我们给了两个整数x和n。我们的任务是编写一个程序来计算pow(x,n)。
让我们举个例子来了解这个问题,
输入值
x = 5 , n = 3
输出结果
125
程序来计算pow(x,n),
示例
#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
该程序显示了一种有效的方法,将幂分为一半,然后将两个部分相乘,然后考虑否定情况。