Fork me on GitHub 打赏

求 pi 的近似值题型汇总

(注:暂时先记录这些问题,后期会持续更新)

一、用格雷戈里公式计算π的近似值,精度要求:最后一项的绝对值小于0.00001

1,用while循环实现

    int denominator,flag;
    double item,pi;
    
    /* 循环初始化 */
    flag = 1;  //flag表示第i项的符号,初始为正 
    denominator = 1;  //denominator第i项的字母,初始为1 
    item = 1.0;  //item中存放第i项的值,初值取1 
    pi = 0;   //置累加和pi的初值为0
    
    while(fabs(item)>=0.00001){
        item = flag*1.0/denominator;  //计算第i项的值
        pi = pi + item;  //累加第i项的值
        flag = -flag;  //改变符号,为下一次循环做准备
        denominator = denominator + 2;  //分母递增2,为下一次循环做准备 
    } 
    pi = pi*4;  //循环计算的结果是 pi/4
    printf("pi=%.4f\n",pi);
    return 0; 

 

2,用函数实现

#include<stdio.h>
#include<math.h>  //程序中要调用绝对值函数,需包含math.h
int main(void)
{
    double e,pi;
    double funpi(double e);  //函数声明

    printf("Enter e:");  //输入精度
    scanf("%lf",&e);
    pi = funpi(e);  //调用函数,把返回值赋值给pi
    printf("pi=%f\n",pi);
    return 0; 
} 

double funpi(double e)  //定义计算pi的函数
{
    int denominator,flag;
    double item,pi;
    
    /* 循环初始化 */
    flag = 1;  //flag表示第i项的符号,初始为正 
    denominator = 1;  //denominator第i项的字母,初始为1 
    item = 1.0;  //item中存放第i项的值,初值取1 
    float sum = 0;   //置累加和sum的初值为0
    
    while(fabs(item)>=e){
        item = flag*1.0/denominator;  //计算第i项的值
        sum = sum + item;  //累加第i项的值
        flag = -flag;  //改变符号,为下一次循环做准备
        denominator = denominator + 2;  //分母递增2,为下一次循环做准备 
    } 
    return sum*4;        
} 

 

posted @ 2017-04-01 19:51  Zoctopus_Zhang  阅读(...)  评论(...编辑  收藏
// function btn_donateClick() { var DivPopup = document.getElementById('Div_popup'); var DivMasklayer = document.getElementById('div_masklayer'); DivMasklayer.style.display = 'block'; DivPopup.style.display = 'block'; var h = Div_popup.clientHeight; with (Div_popup.style) { marginTop = -h / 2 + 'px'; } } function MasklayerClick() { var masklayer = document.getElementById('div_masklayer'); var divImg = document.getElementById("Div_popup"); masklayer.style.display = "none"; divImg.style.display = "none"; } setTimeout( function () { document.getElementById('div_masklayer').onclick = MasklayerClick; document.getElementById('btn_donate').onclick = btn_donateClick; var a_gzw = document.getElementById("guanzhuwo"); a_gzw.href = "javascript:void(0);"; $("#guanzhuwo").attr("onclick","follow('33513f9f-ba13-e011-ac81-842b2b196315');"); }, 900);