编写求x的n次方的递归函数,在主函数调用并输出。(x为double型,n为整型,函数类型为double型)
时间: 2024-02-05 09:12:29 浏览: 36
好的,我明白了。以下是相应的代码实现:
```c++
#include <iostream>
using namespace std;
double pow(double x, int n) {
if (n == 0) {
return 1;
}
double t = pow(x, n / 2);
if (n % 2) {
return x * t * t;
} else {
return t * t;
}
}
int main() {
double x;
int n;
cout << "请输入底数x和指数n: ";
cin >> x >> n;
double res = pow(x, n);
cout << x << "的" << n << "次方为:" << res << endl;
return 0;
}
```
以上的代码中,我们使用了递归的方式实现求x的n次方。主函数中输入了底数x和指数n,然后调用了求幂的函数,并输出结果。在函数内部,如果n为0,则返回1;如果n为奇数,则返回x * (t * t);如果n为偶数,则返回t * t。其中,t代表递归计算中的中间值。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![m](https://img-home.csdnimg.cn/images/20210720083646.png)
![m](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)