用C++写一个函数可以计算x的y次幂
时间: 2023-05-29 10:03:05 浏览: 60
下面是用C语言编写的函数,可以计算x的y次幂:
```c
#include <stdio.h>
double power(double x, int y) {
double result = 1.0;
int i;
for (i = 0; i < y; i++) {
result *= x;
}
return result;
}
int main() {
double x;
int y;
printf("请输入底数x:");
scanf("%lf", &x);
printf("请输入指数y:");
scanf("%d", &y);
printf("%lf的%d次幂为%lf\n", x, y, power(x, y));
return 0;
}
```
在该函数中,我们使用了一个for循环来计算x的y次幂,每次将result乘以x。最后返回result。在主函数中,我们从用户获取x和y的值,并调用power函数计算x的y次幂。最后输出结果。
相关问题
【C++模版】求x的y次幂(函数模版)
以下是求 $x$ 的 $y$ 次幂的函数模板:
```c++
template<typename T>
T power(T x, int y) {
if(y == 0) return 1;
T res = power(x, y / 2);
if(y & 1) return res * res * x;
else return res * res;
}
```
该函数模板可支持任意类型的 $x$,只要该类型支持乘法运算即可。其中,参数 `x` 表示底数,参数 `y` 表示指数。
函数实现采用递归的方式,通过将指数 $y$ 不断折半,快速计算出 $x^y$ 的值。时间复杂度为 $O(\log y)$。
使用示例:
```c++
#include <iostream>
using namespace std;
int main() {
cout << power(2, 10) << endl; // 输出 1024
cout << power(3.14, 2) << endl; // 输出 9.8596
return 0;
}
```
1. 【C++模版】求x的y次幂(函数模版)
以下是一个 C++ 函数模板,用于计算 x 的 y 次幂:
```cpp
template <typename T>
T power(T x, int y) {
T result = 1;
while (y > 0) {
if (y & 1) {
result *= x;
}
x *= x;
y >>= 1;
}
return result;
}
```
该函数接受两个参数:一个类型为 T 的底数 x,和一个类型为 int 的指数 y。函数返回值为类型 T 的 x 的 y 次幂。
该函数使用了二进制指数算法来计算幂次。在每个循环迭代中,它将指数 y 右移一位(相当于除以 2),并将底数 x 平方。如果 y 的最低位为 1,则将结果乘以当前的底数 x。通过这种方式,该算法能够在 O(log y) 的时间复杂度内计算幂次,而不是 O(y)。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)