7-15 计算圆周率 (15point(s)).c

根据下面关系式,求圆周率的值,直到最后一项的值小于给定阈值。

​2​​π​​=1+​3​​1​​+​3×5​​2!​​+​3×5×7​​3!​​+⋯+​3×5×7×⋯×(2n+1)​​n!​​+⋯
输入格式:

输入在一行中给出小于1的阈值。
输出格式:

在一行中输出满足阈值条件的近似圆周率,输出到小数点后6位。
输入样例:

0.01

输出样例:

3.132157
Note : ( 1 ) for the formula is Pi half, asking for is pi, and ( 2 ) observation of odd denominator to know the product, numerator is the factorial of an integer.

//  date:2020/3/6
//  author:xiezhg5
#include <stdio.h>
int main(void)
{
    int i=1;                       //控制变量 
    double a,j=1.0,k=1.0,sum=1.0;  //初始化赋初值 
    scanf("%lf",&a);
    while((k/j)>a)                 //循环条件,最后一项大于阈值 
    {
        j=j*(2*i+1);              //分子为奇数成绩 
        k=k*i;                    //分母为阶乘 
        i++;                      //自增循环 
        sum=sum+(k/j);            //计算圆周率的一半 
    }
    printf("%.6lf",2.0*sum);     //不要忘记乘以2 
    return 0;
}
发布了30 篇原创文章 · 获赞 10 · 访问量 275

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/104693840