利用静态变量求x的n次方的程序
时间: 2024-05-02 14:22:20 浏览: 9
好的,以下是一个利用静态变量求x的n次方的程序:
```
#include <stdio.h>
int power(int x, int n) {
static int result = 1;
if (n == 0) {
result = 1;
} else {
result *= x;
power(x, n - 1);
}
return result;
}
int main() {
int x = 2, n = 5;
printf("%d的%d次方是:%d\n", x, n, power(x, n));
return 0;
}
```
在这个程序中,利用了静态变量result来保存计算结果,每次递归调用函数时都会更新它的值。当n为0时,将result重新赋值为1,避免了递归调用后result值不正确的问题。
相关问题
利用静态局部变量编写函数求n的阶乘
以下是利用静态局部变量编写函数求n的阶乘的示例代码:
```c
int factorial(int n) {
static int result = 1; // 静态局部变量
if (n <= 1) {
int res = result;
result = 1; // 重置静态局部变量
return res;
}
result *= n;
return factorial(n - 1);
}
```
在函数内部,声明了一个静态局部变量 `result`,用于存储计算过程中的阶乘结果。在每次函数调用时,将输入的 `n` 与 `result` 相乘,更新 `result` 的值。当 `n` 小于等于 1 时,将 `result` 的值存储到一个局部变量 `res` 中,并将 `result` 重置为 1,以便下一次函数调用时重新计算阶乘。最后返回 `res` 的值,即为输入 `n` 的阶乘。
使用静态变量求阶乘表
使用静态变量求阶乘表的代码如下:
#include <stdio.h>
long factor(int n2);
void main() {
int n, i;
printf("请输入n的值:");
scanf("%d", &n);
printf("阶乘表如下:\n");
for (i = 1; i <= n; i++) {
printf("%d! = %ld\n", i, factor(i));
}
}
long factor(int n2) {
static long s = 1;
s = s * n2;
return s;
}