求x的n次方编程怎么编

时间:2025-01-25 07:32:29 游戏攻略

C++

方法一:使用循环迭代

```cpp

include

using namespace std;

double power(double x, int n) {

double result = 1.0;

for (int i = 0; i < n; i++) {

result *= x;

}

return result;

}

int main() {

double x = 5;

int n = 2;

cout<< x << " to the power "<< n << " is " << power(x, n) << endl;

return 0;

}

```

方法二:使用递归

```cpp

include

using namespace std;

double power(double x, int n) {

if (n == 0) return 1;

if (n % 2 == 0) return power(x * x, n / 2);

return x * power(x * x, (n - 1) / 2);

}

int main() {

double x = 5;

int n = 2;

cout<< x << " to the power "<< n << " is " << power(x, n) << endl;

return 0;

}

```

方法三:使用内置函数

```cpp

include

include

using namespace std;

int main() {

double x = 5;

int n = 2;

cout<< x << " to the power "<< n << " is " << pow(x, n) << endl;

return 0;

}

```

Python

方法一:使用循环迭代

```python

def power(x, n):

result = 1

for i in range(n):

result *= x

return result

x = 5

n = 2

print(f"{x} to the power {n} is {power(x, n)}")

```

方法二:使用递归

```python

def power(x, n):

if n == 0:

return 1

if n % 2 == 0:

return power(x * x, n // 2)

return x * power(x * x, (n - 1) // 2)

x = 5

n = 2

print(f"{x} to the power {n} is {power(x, n)}")

```

方法三:使用内置函数

```python

x = 5

n = 2

print(f"{x} to the power {n} is {pow(x, n)}")

```

这些示例展示了如何在C++和Python中计算x的n次方,包括使用循环、递归和内置函数的方法。你可以根据具体需求和编程环境选择合适的方法。