`pow` 函数用于计算一个数的幂次方。它的基本语法是 `pow(x, y)`,其中 `x` 是底数,`y` 是指数。`pow` 函数可以处理正整数次幂、负数次幂和取模运算。
计算正整数次幂
```python
result = pow(2, 3)
print(result) 输出 8
```
计算负数次幂
```python
result = pow(10, -2)
print(result) 输出 0.01
```
计算正整数次幂并对另一个数取模
```python
result = pow(3, 2, 5)
print(result) 输出 4
```
在 C 语言中,`pow` 函数的原型是 `double pow(double x, double y)`,它返回 `x` 的 `y` 次幂。需要注意的是,底数和指数都必须是浮点数,指数为 0 时返回 1,底数为 0 且指数不为 0 时返回 0,指数为负数时返回 `1/x` 的 `y` 次方。
```c
include include int main() { double a = 2.5; double b = 3.0; double result = pow(a, b); printf("The result of %.1lf raised to the power of %.1lf is %.1lf\n", a, b, result); return 0; } ``` 输出结果为: ``` The result of 2.5 raised to the power of 3.0 is 15.6 ``` 如果你需要编写一个自定义的 `pow` 函数,可以参考以下示例: ```c include double my_pow(double base, double exponent) { double result = 1.0; if (exponent == 0) { return result; } if (exponent < 0) { base = 1 / base; exponent = -exponent; } while (exponent > 0) { if (exponent % 2 == 1) { result *= base; } base *= base; exponent /= 2; } return result; } int main() { double a = 2.5; double b = 3.0; double result = my_pow(a, b); printf("The result of %.1lf raised to the power of %.1lf is %.1lf\n", a, b, result); return 0; } ``` 这个自定义的 `my_pow` 函数使用循环实现了 `pow` 函数的功能,适用于任何支持浮点数运算的编译器。