task1
(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; }
(2)
#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; printf("%lld\n", p); p = p * n; return p; }
(3)
static变量只赋初值一次,在程序运行时它已经具有值,以后每次调用函数时不再赋初值而保留上次函数调用结束后的值
task2
(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); else { printSymbol(n - 1, symbol); printf("%c", symbol); } }
(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 n, char symbol) { int i; for (i = 1; i <= n; i++) { printf("%c", symbol); } }
task3
#include <stdio.h> long long fun(int n); int main() { int n; long long f; while (scanf("%d", &n) != EOF) { f = fun(n)-1; printf("n = %d, f = %lld\n", n, f); } return 0; } long long fun(int n) { long long t; if (n == 1) { t = 2; } else { t = 2 * fun(n - 1); } return t; }
task4
#include<stdio.h> #include<math.h> int isprime(unsigned int x); int main() { unsigned int y; int k = 0; for (y = 101; y <= 200; y++) { if (isprime(y) == 0) { printf("%u ", y); k++; } } printf("\n"); printf("101~200之间共有%d个非素数",k); } int isprime(unsigned int x) { int i, k; k = sqrt(x); for (i = 2; i <= k; i++) { if (x % i == 0) return 0; else if (i > k) return 1; } }
task5
#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) { unsigned long n = 0, i, k; int t; i = s; k = 1; while (i != 0) { t = i % 10; if (t % 2!=0) { n = n + t * k; k = 10 * k; } i = i / 10; } return n; }
task6
#include <stdio.h> unsigned int jc(unsigned int x); 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; } unsigned int jc(unsigned int x) { unsigned int result; if (x == 0) { result = 1; } else { result = x * jc(x - 1); } return result; } double fun(int n) { int top = 1, botton, m = 1; unsigned int i; double s,sum=0; for (i = 1; i <= n; i++) { botton = jc(i); s = top*1.0 / botton; sum = sum + s*m; m = -m; } return sum; }