3-1
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <windows.h> #define N 80 void printText(int line, int col, char text[]); void printSpace(int n); void printBlankLines(int n); int main() { int line, col, i; char text[N]="hi, May~"; srand(time(0)); for(i=1;i<=10;++i) { line=rand()%25; col=rand()%80; printText(line,col,text); Sleep(1000); } return 0; } void printSpaces(int n) { int i; for(i=1;i<=n;++i) printf(" "); } void printBlankLines(int n) { int i; for(i=1;i<=n;++i) printf("\n"); } void printText(int line, int col, char text[]) { printBlankLines(line-1); printSpaces(col-1); printf("%s",text); }
3-2_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; }
后面的赋值在前一次的值上进行
3-2_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,p1); return 0; } int func(int a,int b) { static int m=0, i=2; i+=m+1; m=i+a+b; return m; }
3-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 n) { long long F,s=1; int i; for(i=0;i<=(n-1);i++) { s=s*2; } F=s-1; return F; }
3-4
#include<stdio.h> #include<string.h> #include <math.h> void move(char x,char y) { printf("%c------>%c\n",x,y); return ; } void HannoiTower(int n,char from,char help,char to) { if(n==1) { move(from,to); } else{ HannoiTower((n-1),from,to,help); move(from,to); HannoiTower((n-1),help,from,to); } } int main() { int num,x; while(scanf("%d",&num)!=EOF) {HannoiTower(num,'A','B','C'); x=pow(2,num)-1; printf("要移动%d次\n",x);} }
3-5
#include <stdio.h> #include <math.h> int is_prime(int n); int main() { int n,i; while(scanf("%d",&n)!=EOF)//输入一个偶数 { for(i=2;i<=n-2;i++)//找素数 { if(is_prime(i)&&is_prime(n-i))//两个素数的和为n if(i<=(n-i)) printf("%d=%d+%d\n",n,i,n-i); } } return 0; } int is_prime(int n) { int p,q=1,j; p=sqrt(n); for(j=2;j<=p;j++) if(n%j==0) q=0; return q; }
3-6
#include <stdio.h> #include <math.h> #define N 1000 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:%d\n\n",t); printf("Enter a number:"); } return 0; } long fun(long s) { int i=0,k; long int a=0;//,a[N],b[N] while(s) { k=s%10; s/=10; if(k%2!=0) { a=a+pow(10,i)*k; i++; } } return a; }