当前位置:   article > 正文

西工大NOJ数据结构实验——1.2高精度计算PI值_高精度计算pi值noj

高精度计算pi值noj

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. #include<math.h>
  5. typedef struct NODE{
  6. int n;
  7. int power;
  8. struct NODE* pre;
  9. struct NODE* next;
  10. }NODE;
  11. void PiCreateAndInitial(NODE* head,int m) {
  12. //创建双向循环链表,并且初始化链表
  13. int tempx=m;
  14. NODE* temp = head;
  15. for (;m>=0;m--){
  16. NODE* p = (NODE*)malloc(sizeof(NODE));
  17. if (p) {
  18. if(m==tempx){
  19. p->n=1;
  20. }else{
  21. p->n=0;
  22. }
  23. p->power=m-tempx;
  24. temp->next = p;
  25. p->pre=temp;
  26. temp = p;
  27. }
  28. }
  29. temp->next=head;
  30. head->pre=temp;
  31. }
  32. void PiOutput(NODE* head,int m) {
  33. //链表的遍历
  34. char s[520]={0};
  35. char *sp=s;
  36. NODE* p = head->next;
  37. while ((m--)>=0) {
  38. *sp=(p->n)+48;
  39. sp=sp+1;
  40. if((p->power)==0){
  41. *sp='.';
  42. sp=sp+1;
  43. }
  44. p = p->next;
  45. }
  46. printf("%s\n",s);
  47. }
  48. void PiMultiply(NODE* head,int n){
  49. //大数乘一个整数
  50. int Cin=0;
  51. NODE* p=head->pre;
  52. while(p!=head){
  53. p->n=(p->n)*n+Cin;
  54. Cin=(p->n)/10;
  55. p->n=(p->n)%10;
  56. p=p->pre;
  57. }
  58. }
  59. void PiDivide(NODE* head,int n){
  60. //大数除一个整数
  61. int temp=0;
  62. NODE* p=head->next;
  63. while(p!=head){
  64. temp=(p->n)%n;
  65. p->n=(p->n)/n;
  66. (p->next)->n=(p->next)->n+10*temp;
  67. p=p->next;
  68. }
  69. }
  70. void PiAdd(NODE* head1,NODE* head2){
  71. //把累加的结果保存下来
  72. NODE* p1=head1->pre;
  73. NODE* p2=head2->pre;
  74. int Cin=0;
  75. while(p1!=head1){
  76. p2->n=(p2->n)+(p1->n)+Cin;
  77. Cin=(p2->n)/10;
  78. p2->n=(p2->n)%10;
  79. p1=p1->pre;
  80. p2=p2->pre;
  81. }
  82. }
  83. int main(){
  84. int m;
  85. scanf("%d",&m);
  86. //完成题目的唯一输入要求
  87. NODE* head1=(NODE*)malloc(sizeof(NODE));
  88. NODE* head2=(NODE*)malloc(sizeof(NODE));
  89. head1->next=head1->pre=NULL;
  90. head2->next=head2->pre=NULL;
  91. if(head1&&head2){
  92. PiCreateAndInitial(head1,750);
  93. PiCreateAndInitial(head2,750);
  94. for(int n=1;n<=5000;n++){
  95. int temp=2*n+1;
  96. PiDivide(head1,temp);
  97. PiMultiply(head1,n);
  98. PiAdd(head1,head2);
  99. }
  100. PiMultiply(head2,2);
  101. PiOutput(head2,m);
  102. }
  103. return 0;
  104. }

5
3.14159

--------------------------------
Process exited after 1.226 seconds with return value 0
请按任意键继续. . .

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/671709
推荐阅读
相关标签
  

闽ICP备14008679号