任务1.1
#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; }
任务1.2
#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变量:静态变量,在函数调用结束后变量的值不会变为初始值。
任务2.1
#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); } if (n >= 2) { printf("%c", symbol); return printSymbol(n - 1, symbol); } }
任务2.2
#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 a, char b) { int i = 1; for (i = 1; i <= a; i++) { printf("%c", b); } }
任务3
#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 a) { if (a == 1) return 1; if (a >= 2) return 2*fun(a - 1)+1; }
任务4
#include<stdio.h> #include<math.h> int isprime(int n); int main() { int i=101,m=0; for (i = 101; i <= 200; i++) { if (!isprime(i)) { m += 1; printf("%5d", i); if (m % 10 == 0) printf("\n"); } } printf("\n101~200之间一共有%d个非素数", m); return 0; } int isprime(int a) { int b = 2; for (b = 2; b <= sqrt(a); b++) if (a % b == 0) return 0; return 1; }
任务5
#include<stdio.h> #include<math.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 a) { long long s=0; int b[100] = { 0 }; int i = 0,c=0,n=0; while (a != 0) { b[i] = a % 10; a /= 10; i++; n++; } for (i=0;i<=n-1;i++) { if (b[i] % 2 != 0) { s += b[i] * pow(10, c); c++; } } return s; }
任务6
#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 = 1,b=1,c=1,d=1; double a=0.0; int k = 1; for (i = 1; i <= n; i++) { for (k = 1; k <= b; k++) { c =c*k; } a += 1.0 /c*d; d = -d; b++; c = 1; } return a; }