首页 > 编程语言 > 详细

c语言:求π的近似值

时间:2016-02-12 06:12:04      阅读:262      评论:0      收藏:0      [点我收藏+]

用公式π/4=1-1/3+1/5-1/7...求π的近似值,直到发现某一项的绝对值小于10^6为止(该项不累加)

解:程序:

#include<stdio.h>

#include<math.h>

int main()

{

int sign = 1;

double pi = 0.0, n = 1.0, term = 1.0;//term表示当前项

while (fabs(term) >= 1e-6)

{

pi += term;

n += 2;

sign = -sign;

term = sign / n;

}

pi *= 4;

printf("pi=%10.8f\n", pi);

return 0;

}

结果:

pi=3.14159065

请按任意键继续. . .

本程序输出的结果是pi=3.14159065,虽然输出了8位小数,但是只有前5位小数3,14159是准确的,因为第7位已经小于10^-6,后面的项没有累加。

再看如下两个精度不同的程序:

程序1:

#include<stdio.h>

#include<math.h>

int main()

{

int sign=1;

int count = 0;

double pi = 0.0, n = 1.0, term = 1.0;//term表示当前项

while(fabs(term)>=1e-6)

{

count++;

pi += term;

n += 2;

sign = -sign;

term = sign / n;

}

pi *= 4;

printf("pi=%10.8f\n",pi);

printf("count=%d\n",count);

return 0;

}

结果:

pi=3.14159065

count=500000

请按任意键继续. . .

程序2:

#include<stdio.h>

#include<math.h>

int main()

{

int sign=1;

int count = 0;

double pi = 0.0, n = 1.0, term = 1.0;//term表示当前项

while(fabs(term)>=1e-8)//变化部分

{

count++;

pi += term;

n += 2;

sign = -sign;

term = sign / n;

}

pi *= 4;

printf("pi=%10.8f\n",pi);

printf("count=%d\n",count);

return 0;

}

结果:

pi=3.14159263

count=50000000

请按任意键继续. . .

精度不同,运行时间不同,程序2精度更高,但是运行次数是程序1的100倍。


本文出自 “岩枭” 博客,请务必保留此出处http://yaoyaolx.blog.51cto.com/10732111/1741580

c语言:求π的近似值

原文:http://yaoyaolx.blog.51cto.com/10732111/1741580

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!