int fun(int m, int n) { int c=0; static int b=2; if(m<b || n<b) return m*n; else if(m%b==0 && n%b==0) {c=b; return c*fun(m/b,n/b);} else {b++; return fun(m,n);} } 这个函数的作用
时间: 2023-06-27 17:07:38 浏览: 79
这个函数名为 `fun`,接受两个整型参数 `m` 和 `n`。其作用是计算 `m` 和 `n` 的最大公约数。
具体实现过程为:
1. 初始化变量 `c` 和 `b`,其中 `c` 初始值为 0,`b` 初始值为 2。
2. 如果 `m` 或 `n` 中有一个小于 `b`,则直接返回 `m*n`。
3. 如果 `m` 和 `n` 都能被 `b` 整除,则将 `c` 的值赋为 `b`,并递归调用 `fun(m/b, n/b)`,将返回值乘以 `c`。
4. 如果 `m` 和 `n` 都不能被 `b` 整除,则将 `b` 加 1,再递归调用 `fun(m, n)`。
该函数使用了递归算法实现,通过不断缩小 `m` 和 `n` 的值来求解它们的最大公约数。
相关问题
#include <stdio.h> fun(int x){ static int a=3; a=x; return(a); int main(){ int k=2,m=1,n; n=fun(k); m=fun(m); printf("%d%d",n,m); return 0; }
这段代码存在语法错误,正确的代码如下:
```c
#include <stdio.h>
int fun(int x){
static int a=3;
a=x;
return(a);
}
int main(){
int k=2,m=1,n;
n=fun(k);
m=fun(m);
printf("%d%d",n,m);
return 0;
}
```
这段代码的输出结果是:22,因为在函数 `fun` 中,变量 `a` 是 `static` 类型的,意味着它只会被初始化一次,后续调用该函数时不会重新初始化。因此,第一次调用 `fun` 时 `a` 值被赋为 2,第二次调用 `fun` 时 `a` 值被赋为 1,所以 `n` 和 `m` 的值都为 2。
C语言static int b的代码例子
以下是一个示例代码:
```c
#include <stdio.h>
void fun() {
static int b = 0; // 静态局部变量
b++;
printf("b = %d\n", b);
}
int main() {
fun(); // b = 1
fun(); // b = 2
fun(); // b = 3
return 0;
}
```
在上面的代码中,`fun()`函数中声明了一个静态局部变量`b`,并进行自增操作。在`main()`函数中调用`fun()`函数三次,每次调用都会输出`b`的值。可以看到,`b`的值会一直保留下来,而不是在每次调用`fun()`函数时都重新初始化为0。这是因为静态局部变量的生命周期与程序的生命周期相同,即它们在程序开始运行时被初始化,直到程序结束时才被销毁。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)