• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

# 实验4

2周前 (04-29) 8次浏览
```#include <stdio.h>
long long fun(int n); // 函数声明
int main() {
int n;
long long f;
while(scanf("%d", &n) != EOF) {
f = fun(n); // 函数调用
printf("n = %d, f = %lldn", n, f);
}
return 0;
}
long long fun(int n){
if(n==1)
return 1;
else
return 2*fun(n-1)+1; //递归
}```

```// 利用局部static变量计算阶乘
#include <stdio.h>
long long fac(int n); // 函数声明
int main() {
int i,n;

printf("Enter n: ");
scanf("%d", &n);

for(i=1; i<=n; ++i)
printf("%d! = %lldn", i, fac(i));

return 0;
}
// 函数定义
long long fac(int n) {
static long long p = 1;

p = p*n;
printf("p = %lldn", p);
return p;
}```

```#include<stdio.h>
int func(int, int);
int main() {
int k=4,m=1,p1,p2;
p1 = func(k,m) ;
p2 = func(k,m) ;
printf("%d,%dn",p1,p2) ;
return 0;
}
int func(int a,int b) {
static int m=0,i=2;
i += m+1;
m = i+a+b;

return (m);
}```

static就是只对变量初始化一次 以后不再初始化 使用上一次的结果

func函数调用过一次之后 static不再对i和m初始化 i和m用上一次执行后的值去计算 此时i=i+m+1=3+8+1=12 第二个结果是m=i+a+b=12+4+1=17

```#include<stdio.h>
#define N 1000

int fun(int n, int m, int bb[N]) {
int i, j, k = 0, flag;

for (j = n; j <= m; j++) {
flag = 1;
for (i = 2; i < j; i++)
if (j % i == 0) {
flag = 0;
break;
}
if (flag == 1)
bb[k++] = j;
}
return k;
}

int main() {
int n = 0, m = 0, i, k, bb[N];

while (scanf("%d %d", &n, &m) != EOF) {

for (i = 0; i < m - n; i++)
bb[i] = 0;

k = fun(n, m, bb);

for (i = 0; i < k; i++)
printf("%4d", bb[i]);
printf("n");
}

return 0;
}```

```#include <stdio.h>
void dec2n(int x, int n);  // 函数声明

int main() {
int x;

printf("输入一个十进制整数: ");
scanf("%d", &x);

dec2n(x, 2);
dec2n(x, 8);
dec2n(x, 16);

return 0;
}

void dec2n(int x, int n) {
int i, m;
char a[100];
for (i = 0;x != 0;i++) {
a[i] = x%n;
x = x / n;
}
if (a[i]>9)
switch (a[i]){
case 10:a[i] = 'A';break;
case 11:a[i] = 'B';break;
case 12:a[i] = 'C';break;
case 13:a[i] = 'D';break;
case 14:a[i] = 'E';break;
case 15:a[i] = 'F';break;
}
for (m = i - 1;m >= 0;m--)
printf("%X", a[m]);
printf("n");
}```