实验3
任务一
#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!=%lld\n", i, fac(i)); return 0; } long long fac(int n) { static long long p = 1;
p = p * n; 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,%d\n", 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:一次函数调用结束时,该数据不会消失,而是继续被调用,直到程序运行结束。
任务二
迭代
#include<stdio.h> void printSymbol(int n, char symbol); int main() { int n; char symbol; while( scanf("%d %c", &n, &symbol) != EOF ) { printSymbol(n, symbol); printf("\n"); } return 0; } void printSymbol(int n, char symbol) { int i; for(i=1;i<=n;i++) { printf("%c",symbol); } }
递归
#include<stdio.h> void printSymbol(int n, char symbol); int main() { int n; char symbol; while( scanf("%d %c", &n, &symbol) != EOF ) { printSymbol(n, symbol); printf("\n"); } return 0; } void printSymbol(int n, char symbol) { if(n==1) printf("%c",symbol); else { printSymbol(n-1,symbol); printf("%c",symbol); } }
任务三
#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 = %lld\n", n, f); } return 0; } long long fun(int n) { long long m; if(n==1) m = 1; else m = fun(n-1)*2+1; return m; }
任务四
#include<stdio.h> #include<math.h> int isPrime(int n); int main() { int n,j,count=0; for(n=101;n<=200;n++) { j = isPrime(n); if(j==0) { printf("%5d",n); count++; } } printf("\n101~200之间一共有%d个非素数",count); return 0; } int isPrime(int n) { int k; for(k=2;k<=sqrt(n);k++) { if(n%k==0) return 0; } return 1; }
任务五
#include<stdio.h> long fun(long s); int main() { long s, t; printf("Enter a number: "); while (scanf("%ld", &s) != EOF) { t = fun(s); printf("new number is: %ld\n\n",t); printf("Enter a number: "); } return 0; } long fun(long s) { long x=0,i; int t; i=1; while(s) { t=s%10; if(t%2!=0) { x=x+t*i; i=i*10; } s=s/10; } s=x; }
任务六
#include<stdio.h> double fun(int n); int main() { int n; double s; printf("Enter n(1~10): "); while (scanf("%d", &n) != EOF) { s = fun(n); printf("n = %d, s = %f\n\n", n, s); printf("Enter n(1~10): "); } return 0; } double fun(int n) { int i; double x=-1,y=0; for(i=1;i<=n;i++) { x=-x*i; y=y+1/x; } return y; }
总结:递归是重复调用函数自身实现循环。迭代是函数内某段代码实现循环;迭代时,会当前保存的结果作为下一次循环计算的初始值。