上完课过来整理一下笔记555
1、穷举法
1 //百钱买百鸡问题(简化后) 2 3 #include4 #include 5 6 int main() 7 { 8 int i,j,k; 9 for(i=0; i<20; i++) 10 { 11 for(j=0; j<34; j++) 12 { 13 k=100-i-j; 14 if(i*15+j*9+k==300) 15 { 16 printf("%d %d %d\n",i,j,k); 17 } 18 } 19 } 20 return 0; 21 }
2、迭代法
1 //求解一元三次方程指定范围的根 2 #include3 #include 4 #include 5 6 double biroot(double,double); 7 double foo(double); 8 9 int main() 10 { 11 double x1,x2; 12 do 13 { 14 scanf("%lf%lf",&x1,&x2); 15 }while(foo(x1)*foo(x2)>0); 16 17 printf("%.2f\n",biroot(x1,x2)); 18 return 0; 19 } 20 double biroot(double x1,double x2) 21 { 22 double ret; 23 do 24 { 25 ret=(x1+x2)/2; 26 if(foo(ret)*foo(x1)>0) 27 { 28 x1=ret; 29 } 30 else 31 { 32 x2=ret; 33 } 34 }while(fabs(x1-x2)>=1e-7); 35 ret=(x1+x2)/2; 36 return ret; 37 } 38 double foo(double x) 39 { 40 return(x*x*x-7.7*x*x+19.2*x-15.3); 41 }
3、牛顿迭代(牛顿切线法)
//求解一元三次方程在1.0附近的根 #include#include #include double ntroot(double); double foo(double); double dfoo(double); int main() { double x0; scanf("%lf",&x0); printf("%.2f\n",ntroot(x0)); return 0; } double ntroot(double x) { double x0; double f,df; do { x0=x; f=foo(x0); df=dfoo(x0); x=x0-f/df; } while(fabs(x-x0)>=1e-7); return x; } double foo(double x) { return (x*x*x-7.7*x*x+19.2*x-15.3); } double dfoo(double x) { return(3.0*x*x-15.4*x+19.2); }
4、递推法(归纳法)
//累加和累乘 #include#include #include double getSum(int); int main() { int n; scanf("%d",&n); printf("%f\n",getSum(n)); return 0; } double getSum(int n) { int i; double s=0.0; for(i=1;i<=n;i++) { s+=pow(-1,i+1)/i; } return s; }
//筛选法求素数 #include#include #define MAX_SIZE 1000 void getPrimeTab(int *,int); void initSieve(int*,int); int getNext(int*,int,int); int outPrimeTab(int *,int); int main() { int n; int cnt; int sieve[MAX_SIZE]={0}; initSieve(sieve,MAX_SIZE); scanf("%d",&n); getPrimeTab(sieve,n); cnt=outPrimeTab(sieve,n); printf("total primes = %d\n",cnt); return 0; } void initSieve(int*ps,int n) { int i; for(i=2;i ) { ps[i]=1; } } int outPrimeTab(int *ps,int n) { int i,count=0; for(i=2;i ) { if(ps[i]==1) { if(count++%6==0) { printf("\n"); } printf("%8d",i); } } printf("\n"); return count; } int getNext(int*ps,int p,int n) { int q=p+1; while(q 0) { q++; } return q; } void getPrimeTab(int *ps,int n) { int p,q,i; for(p=2;p*p getNext(ps,p,n)) { for(q=p;p*q getNext(ps,q,n)) { for(i=p*q;i p) { ps[i]=0; } } } }
//梯形法求定积分 #include#include #include double integrate(double(*pf)(double),double a,double b,int n); double my_fun(double x); int main() { double a,b; int n; printf(" 积分上限: a= "); scanf("%lf",&a); printf(" 积分下限 :b= "); scanf("%lf",&b); printf(" 分割段数 : n= "); scanf("%d",&n); printf("sin 函数积分值: %f\n",integrate(sin,a,b,n)); printf("x^2 函数积分值: %f\n",integrate(my_fun,a,b,n)); return 0; } double integrate(double(*pf)(double),double a,double b,int n) { int i; double h=(b-a)/n; double s=(pf(a)+pf(b))/2; for(i=1;i<=n-1;i++) { s+=pf(a+i*h); } s=h*s; return s; } double my_fun(double x) { return x*x; }