資料結構28——高精度計算PI值
阿新 • • 發佈:2019-02-19
題目:輸入n,輸出PI精確到小數點後n位的PI值。
#include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node*next; struct node*pre; }node,*list; int n; void init(list &l) { list tail = l, p; int i = 0; p=(list)malloc(sizeof(node)); tail->next = p; p->pre = tail; tail = p; p->data = 2; tail->next = NULL; } void destorylist(list &l) { list p=l->next; list q; while (p->next) { q = p->next; free(p); p = q; } free(l); l = NULL; } void insert(list &l, int data) { list p = l; if(p == NULL) { return; } else { while (p->next) p = p->next; list temp = (list)malloc(sizeof(node)); p->next = temp; temp->data = data; temp->pre = p; temp->next = NULL; } } void tran(list l) { printf("%d.",l->next->data); l=l->next; list p; p=l->next; while(p!=NULL&&n) { printf("%d",p->data); p=p->next; n--; } printf("\n"); } int main() { list p,sum1; int i; scanf("%d",&n); p=(list)malloc(sizeof(node)); sum1=(list)malloc(sizeof(node)); p->next = NULL; sum1->next=NULL; p->pre = NULL; sum1->pre=NULL; init(p); init(sum1); for(i=1;i<=1000;i++) { insert(p,0); insert(sum1,0); } list q,sum; int ret,tmp,cnt=3,num=1; int flag=1; while(flag) { q=p->next; sum=sum1->next; ret=0; while(q->next) { q=q->next; } while (q) { tmp=q->data*num+ret; q->data=tmp%10; ret=tmp/10; if(q->pre==NULL)break; else { q=q->pre; } } ret=0; q=p->next; while (q) { tmp=q->data+ret*10; q->data=tmp/cnt; ret=tmp%cnt; if(q->next==NULL)break; else { q=q->next; } } q=p->next; sum=sum1->next; while(q->next&&sum->next) { q=q->next; sum=sum->next; } flag=0; while (q&&sum) { tmp=sum->data+q->data ; sum->data=tmp%10; if(sum->pre==NULL||q->pre==NULL) { break; } else { sum->pre->data+=tmp/10; flag |= q->data; sum=sum->pre; q=q->pre; } } num++; cnt+=2; } tran(sum1); destorylist(p); destorylist(sum1); return 0; }