二分法,素数和单链表
15. 以下程序求方程的一个近似根。root函数采用二分法计算并返回方程f(x)=0在[a,b]内的一个近似根,main函数调用root函数求方程cos(x)=0在[0,3.14]内的一个近似根。试完善程序以达到要求的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include<stdio.h> #include<math.h> double root(double a,double b,double(*f)(double)) { double x,y; if((19)) { printf("There is no root between%f and%f",a,b); return 0; } do { x=( 20 ); y=f(x); if(fabs(y)<1e-6||fabs(b-a)<le-6) break; if((21)<0)b=x; else a=x; } while(1); return x; } void main() { printf("\n x=%f",root(0,3.14,(22)); } |
16. 以下程序在3-50范围内验证:大于等于3的两个相邻素数的平方之间至少有4个素数。例如,3和5是相邻素数,3^2~5^2之间有素数11、13、17、19、23。试完善程序以达到要的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include<stdio.h> #include<stdlib.h> #include<math.h> int prime(int n) { int i; for(i=2; i<=sqrt(n); i++) if((23)) return 0; return 1; } void main() { int i,j,k=0,m,n,c,a[30]= {0}; for(i=3; i<50; i++) if(prime(i)) (24) ; for(i=0; i<k-1; i++) { m=a[i]*a[i]; n=a[i+1]*a[i+1]; c= (25) ; for(j=m+1; j<n; j++) if((26)) c++; if(c>=4) printf("\n %d*%d-%d*%d:%d",a[i],a[i],a[i+1],a[i+1],c); else { printf("Error"); exit(0); } } } |
17. fun函数的功能是删除s指向的链表中满足以下条件的结点:该结点的编号值是奇数且存放的字母ASCII编码值也为奇数(提示:a的ASCII编码是97);将删除的结点添加到t所指向的链表尾部。试完善fun函数以达到要求的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include<stdio.h> struct node { int i; /* 存放结点的编号 */ char c; /* 存放结点的编号 */ struct node *next; }; struct node *t=NULL; struct node *fun(struct node *s) { struct node *p,*q; struct node *r; p=q=s; while(p!=NULL) { if(((p->i)%2)&&((p->c)%2)) { if(s==p) s=q=( 27 ); else { ( 28 ) ; q=p->next; } if(t==NULL) t=r=p; else { r->next=p; r=r->next; } } p=(29) ; } if(t!=NULL) ( 30 ) ; return s; } |