1 #include<stdio.h> 2 #include<stdlib.h> 3 long long fac(int n); 4 //利用局部变量static的特性,计算阶乘 5 int main(){ 6 int i,n; 7 printf("Enter n:"); 8 scanf("%d",&n); 9 10 for(i=1;i<=n;++i){ 11 printf("%d!=%11d\n",i,fac(i)); 12 } 13 system("pause"); 14 return 0; 15 } 16 long long fac(int n) 17 { 18 static long long p=1; 19 p=p*n; 20 return p; 21 }
#include<stdio.h> #include<stdlib.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); system("pause"); return 0; } int func(int a, int b) { static int m=0,i=2; i+=m+1; m=i+a+b; return (m); }
总结:static变量只在最初赋值一次,后面再通过static赋值时变量值不变
#include<stdio.h> #include<stdlib.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"); } system("pause"); return 0; } void printSymbol(int n,char symbol){ int a=1; for(a=1;a<=n;a++){ printf("%c",symbol); }}
#include<stdio.h> #include<stdlib.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"); } system("pause"); return 0; } void printSymbol(int n,char symbol){ int a=1; if(n==1) printf("%c",symbol); else {printf("%c",symbol); printSymbol(n-1,symbol);} }
#include<stdio.h> #include<stdlib.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=%11d\n",n,f); } system("pause"); return 0;} long long fun(int n){ long a=1; if(n==1) a=1; else a=2*fun(n-1)+1; return a;}
#include<stdio.h> #include<stdlib.h> int isPrime(int a); int main(){ int a,b; a=0; for(b=101;b<=200;b++){ if(isPrime(b)==1) {printf("%4d",b); a++;} } printf("\n素数有%d个",a); system("pause"); return 0; } int isPrime(int a){ int b; for(b=2;b<=15;b++){ if(a%b==0){a=1;break;} } return a;}
#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 a,b,c,d; d=1; b=0; for(a=1;(s/a)>=1;a=a*10) { if((s/a)%2==1){ b=b+d*((s/a)%10); d=d*10; } } return b; }
#include<stdio.h> double fun(int n); int main(){ int n; double s; printf("Enter n(1~10):"); while (scanf("%ld",&n)!=EOF){ s=fun(n); printf("n=%d,s=%f\n\n",n,s); } return 0; } double fun(int n) { int a,b,c,e; double d,ans; ans=0.0; b=1; e=1; for(a=1;a<=n;a++){ c=1; for(b=1;b<=a;b++){ c=c*b; } d=1.0*e/c; e=-e; ans=ans+d; } return ans; }