实验3
#include <stdlib.h> #include <time.h> #include <windows.h> #define N 80 void print_text(int line, int col, char text[]); void print_spaces(int n); void print_blank_lines(int n); int main() { int line, col, i; char text[N] = "hi, November~"; srand(time(0)); for(i = 1; i <= 10; ++i) { line = rand() % 25; col = rand() % 80; print_text(line, col, text); Sleep(1000); } return 0; } void print_spaces(int n) { int i; for(i = 1; i <= n; ++i) printf(" "); } void print_blank_lines(int n) { int i; for(i = 1; i <= n; ++i) printf("\n"); } void print_text(int line, int col, char text[]) { print_blank_lines(line-1); print_spaces(col-1); printf("%s", text); }
任务1:间隔相同时间在随机一行的随机一列输出一段文本。
任务2:
局部变量static变量会使p的值在每循环一次之后保留上一次循环得到的值;静态局部变量只被初始化一次,下一次运算依据上一次的结果值。
任务3:
#include <stdio.h> long long func(int n); // 函数声明 int main() { int n; long long f; while (scanf("%d", &n) != EOF) { f = func(n); // 函数调用 printf("n = %d, f = %lld\n", n, f); } return 0; } long long func(int n) { if(n==0) return 0; else return 2*func(n-1)+1; }
任务4:
#include <stdio.h> int func(int n, int m); int main() { int n, m; while(scanf("%d%d", &n, &m) != EOF) printf("n = %d, m = %d, ans = %d\n", n, m, func(n, m)); return 0; } int func(int n,int m) { int ans,i,p=1,q=1,f=1; for(i=1;i<=n;i++) { p*=i; } for(i=1;i<=m;i++) { q*=i; } for(i=1;i<=(n-m);i++) { f*=i; } ans=p/(q*f); return ans; }
#include <stdio.h> int func(int n, int m); int main() { int n, m; while(scanf("%d%d", &n, &m) != EOF) printf("n = %d, m = %d, ans = %d\n", n, m, func(n, m)); return 0; } int func(int n, int m) { if(n<m) return 0; if(n==m||m==0) return 1; else return func(n-1,m)+func(n-1,m-1); }
任务5:
#include <stdio.h> #include<stdlib.h> void hanoi(unsigned int n,char from,char temp,char to); void moveplate(unsigned int n,char from,char to); int bushu; int main() { unsigned int n; while(scanf("%u",&n)!=EOF) { bushu=0; hanoi(n,'A','B','C'); printf("一共移动了 %d 次\n",bushu); } return 0; } void hanoi(unsigned int n,char from,char temp,char to) { bushu++; if(n==1) moveplate(n,from,to); else { hanoi(n-1,from,to,temp); moveplate(n,from,to); hanoi(n-1,temp,from,to); } } void moveplate(unsigned int n,char from,char to) { printf("%u:%c-->%c\n",n,from,to); }
实验6
#include <stdio.h> #include <math.h> #define N 100 long func(long s); int main() { long s, t; printf("Enter a number: "); while (scanf("%ld", &s) != EOF) { t = func(s); printf("new number is: %ld\n\n", t); printf("Enter a number: "); } return 0; } long func(long s) { int p;long q=1,sum=0; while(s>0) { p=s%10; s/=10; if(p%2!=0) { sum+=q*p; q*=10; } } return sum; }