7-50 近似求PI(15 分)

题目:

本题要求编写程序,根据下式求π的近似值,直到最后一项小于给定精度eps

π 2 = 1 + 1 ! 3 + 2 ! 3 × 5 + + i ! 3 × 5 × ( 2 i + 1 ) .

输入格式:
输入在一行中给出精度 eps,可以使用以下语句来读输入:
scanf("%le", &eps);
输出格式:
在一行内,按照以下格式输出π的近似值(保留小数点后5位):
PI = 近似值
输入样例:
1E-5
输出样例:
PI = 3.14158

代码:

#include <stdio.h>

int main(){
    double eps, sum=1, i, temp=1;
    scanf("%le", &eps);
    for(i=1; temp>eps; i++){
        temp = temp*i/(2*i+1);
        sum += temp;
    }
    printf("PI = %.5f\n", 2*sum);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36913610/article/details/81173389
今日推荐