zoukankan      html  css  js  c++  java
  • 8. C语言求圆周率π(三种方法)

    题目1) 利用公式①计求π的近似值,要求累加到最后一项小于10^(-6)为止。

    题目2) 根据公式②,用前100项之积计算π的值。

    题目1)提供了一种解法,题目2)提供了两种解法,请看解析。

    题目1)的代码:

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <math.h>
     4 int main(){
     5     float s=1;
     6     float pi=0;
     7     float i=1.0;
     8     float n=1.0;
     9     while(fabs(i)>=1e-6){
    10         pi+=i;
    11         n=n+2;
    12         // 这里设计的很巧妙,每次正负号都不一样 
    13         s=-s; 
    14         i=s/n;
    15     }
    16     pi=4*pi;
    17     printf("pi的值为:%.6f
    ",pi);
    18     
    19     return 0;
    20 }

    运行结果:

    pi的值为:3.141594

    上面的代码,先计算π/4的值,然后再乘以4,s=-s; 用的很巧妙,每次循环,取反,结果就是,这次是正号,下次就是负号,以此类推。

    题目2)的代码[代码一]:

     1 #include <stdio.h>
     2 #include <math.h>
     3 int main(){
     4     float pi=1;
     5     float n=1;
     6     int j;
     7     for(j=1;j<=100;j++,n++){
     8         if(j%2==0){
     9             pi*=(n/(n+1));
    10         }else{
    11             pi*=((n+1)/n);
    12         }
    13     }
    14     pi=2*pi;
    15     printf("pi的值为:%.7f
    ",pi);
    16  
    17     return 0;
    18 }

    运行结果:

    pi的值为:3.1260781

    此算法的主要思想:
    观察分子数列:
    a1=2  a2=2
    a3=4  a4=4
    a5=6  a6=6
    ......
    由此得知,当n为偶数时,an=n;当n为奇数时,an=a(n+1)=n+1;

    同理观察分子数列:
    b1=1 b2=3
    b3=3 b4=5
    b5=5 b6=7
    b7=7 b8=9.......
    由此可知,当n为奇数时,bn=n,当n为偶数时,bn=b(n+1)。
    综上可知,当n为奇数时,每次应乘以(n+1)/n。当n为偶数时,每次应乘以n/(n+1)。

    题目2)的代码[代码二]:

     1 #include <stdio.h>
     2 #include <math.h>
     3  
     4 int main(){
     5     float term,result=1;
     6     int n;
     7     for(n=2;n<=100;n+=2){
     8         term=(float)(n*n)/((n-1)*(n+1));
     9         result*=term;
    10     }
    11     printf("pi的值为:%f
    ", 2*result);
    12     
    13     return 0;
    14 }

    运行结果:

    pi的值为:3.126079

    算法思想:采用累乘积算法,累乘项为term=n*n/((n-1)*(n+1)); n=2,4,6,...100。步长为2。


    感谢你的阅读,请用心感悟!更多内容请关注微信公众号:C语言自学网  ;希望可以帮到爱学习的你!!分享也是一种快乐!!!请接力。。。

    点击查看原文,谢谢!

  • 相关阅读:
    Python Twelfth Day
    Python Tenth Day
    Python Ninth Day
    Python Eighth Day
    Python Seventh Day
    Python Sixth Day
    Python Fifth Day
    Python Fourth Day
    Python Third Day
    金融量化分析-python量化分析系列之---使用python的tushare包获取股票历史数据和实时分笔数据
  • 原文地址:https://www.cnblogs.com/kangyifan/p/13506050.html
Copyright © 2011-2022 走看看